用单链表实现队列

typedef struct node
{
	int data;
	node *next;
}node;

typedef struct queue
{
	node* front;
	node* rear;
}Queue;

Queue* CreateQueue()  // 创建空队列
{
	Queue *q = new Queue;
	q->front = NULL;
	q->rear = NULL;
	return q;
}

void push(Queue *q, int value)   // 向队尾插入元素
{
	node* newP = new node;
	assert(newP !=NULL);
	newP->data = value;
	newP->next = NULL;

	if (q->rear == NULL)   // 队空
	{
		q->front = q->rear = newP;
	}
	else
	{
		q->rear->next = newP;
		q->rear = newP;
	}
}

void pop(Queue *q)
{
	node* p = NULL;
	if (q->rear == NULL)
	{
		std::cout << "队列已空" << std::endl;
	}
	else if(q->front == q->rear && q->front != NULL)
	{
		p = q->front;
		q->front = q->rear = NULL;
	}
	else
	{
		p = q->front;
		q->front = q->front->next;
	}
	delete p;
	p = NULL;
}

int length(Queue *q)
{
	node* p = NULL;
	int len = 0;
	if (q->rear != NULL)  // 队列非空
	{
		p = q->front;
		while (p != q->rear)
		{
			len++;
			p = p->next;
		}
		len++;
	}
	return len;
}

void print(Queue *q)
{
	node* p = NULL;
	if (q->rear != NULL)  // 队列非空
	{
		p = q->front;
		while (p != q->rear)
		{
			std::cout << p->data << " ";
			p = p->next;
		}
		std::cout << p->data << std::endl;
	}
	else
	{
		std::cout << "空队列" << std::endl;
	}
}

 

你可能感兴趣的:(C++笔记)