每日一题Day45

基于循环链表的队列的基本操作

描述

用带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点(不设头指针)。实现该队列的入队出队以及判断队列是否为空操作。

输入

多组数据,每组数据有两行。第一行为两个整数n和m,n表示入队序列A的长度(n个数依次连续入队,中间没有出队的情况),m表示出队序列B的元素数量(m个数依次连续出队,中间没有入队的情况)。第二行为序列A(空格分隔的n个整数)。当n和m都等于0时,输入结束。

输出

对应每组数据输出一行。每行包括m+1个整数,前m个数代表出队序列B的各个整数,最后一个整数表示队列是否为空,队列为空输出0,不为空输出1。整数之间用空格分隔。

样例输入1 

5 3
1 3 5 3 6
4 4
-1 2 3 4
0 0

样例输出1

1 3 5 1
-1 2 3 4 0

解答:建立循环链表队列,根据输入执行入栈出栈操作。注意当最后一个元素出栈时,修改队尾指针指向头结点。

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int data;
	struct node *next;
} Node,*List;

void Init(List &L)
{
	L=(Node *)malloc(sizeof(Node));
	L->next=L;
}

void Push(List &L,int x)
{
	Node *p=(Node *)malloc(sizeof(Node));
	p->data=x;
	p->next=L->next;
	L->next=p;
	L=p;
}

void Pop(List &L)
{
	Node *q;
	q=L->next->next;
	printf("%d ",q->data);
	L->next->next=q->next;
	if(q == L)
		L=L->next;
	free(q);
}

int isEmpty(List L)
{
	return L->next == L?1:0;
}

int main()
{
	int n,m,x;
	List L;
	while(1)
	{
		scanf("%d %d",&n,&m);
		if(n==0 && m==0)
			break;
		Init(L);
		while(n--)
		{
			scanf("%d",&x);
			Push(L,x);
		}
		while(m--)
		{
			Pop(L);
		}
		if(isEmpty(L))
			printf("0\n");
		else
			printf("1\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZLambert/article/details/81808040
今日推荐