typedef int Datatype;
typedef struct queue
{
	Datatype data;
	struct queue* next;
}queue;
//队列
typedef struct
{
	queue* rear;
}LinkQueue;
//初始化
void queueinit(LinkQueue* ps)
{
	ps->rear = (queue*)malloc(sizeof(queue));
	if (ps->rear == NULL)
	{
		perror("error");
		exit(1);
	}
	ps->rear->next = ps->rear;//初始化循环链表
}
//判空
int Empty(LinkQueue* ps)
{
	return ps->rear == ps->rear->next;//头尾相等,为空
}
//入队
int push(LinkQueue* ps, int e)
{
	queue* newnode = (queue*)malloc(sizeof(queue));
	if (newnode == NULL)
	{
		perror("error:");
		exit(1);
	}
	newnode->data = e;
	newnode->next = ps->rear->next;//新节点指向原队首
	ps->rear->next = newnode;
	if (ps->rear == ps->rear->next)
	{
		ps->rear = newnode;
	}
}
int pop(LinkQueue* ps)
{
	if ((Empty(&ps)))
	{
		printf("栈为空,无输出内容\n");
		return -1;
	}
	//出队是头出,
	queue* temp = ps->rear->next;//临时节点指向队首
	int ret = temp->data;
	ps->rear->next = temp->next;//尾节点直接指向原队首的下一个节点
	if (ps->rear->next == ps->rear)
	{
		ps->rear->next = ps->rear;
	}
	free(temp);
	return ret;
}

int main()
{
	LinkQueue ps;
	queueinit(&ps);
	push(&ps, 1);
	push(&ps, 2);
	printf("出队情况\n");
	printf("%d\n", pop(&ps));
	printf("%d\n", pop(&ps));
	int ret = Empty(&ps);
	if (ret == 1)
	{
		printf("队列元素已全出队\n");
	}
	return 0;
}

更多推荐