队列(数据结构)

自己尝试写了一个队列。
采用递归定义

#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<iostream>
using namespace std;
struct stack
{
	int v;				//队列元素存储的值
	stack *next;			//队列下一个元素
}*back=NULL,*front=NULL;			//一个指向队首,一个指向队尾
void push(int v)			//入队
{		
	if(front==NULL)
	{
		back=(stack *)malloc(20);
		back->v=v;
		back->next=NULL;
		front=back;
	}
	else
	{
		stack *temp=(stack *)malloc(20);
		temp->v=v;		temp->next=NULL;
		back->next=temp;		back=temp;
	}//printf("%d\n",(*top).v);
}
void pop()			//出队
{
	if(front==NULL)
		return;
	else
	{
		stack *temp=front->next;
		free(front);
		front=temp;
	}//printf("%d\n",(*top).v);
}
int size()			//测量队列长度
{
	int num=0;
	stack *p,*temp;
	p=front;
	while(p!=NULL)
	{
		num++;
		temp=p->next;
		p=temp;
	}//cout<<'a'<<endl;
	return num;
}
bool empty()			//测试队尾是否为空
{
	return front==NULL;
}
void clear()				//清空队列
{
	while(front!=NULL)
	{
		stack *temp;
		temp=front->next;
		free(front);
		front=temp;
	}
}
int main()
{
	int n,i,m;
	while((cin>>n)&&n)
	{
		for(i=1;i<=n;i++)
		{
			cin>>m;
			push(m);			//测试push()函数
		}
		cout<<size()<<endl;			//测试size()函数
		for(i=1;i<=n;i++)
		{
			cout<<front->v<<' '<<back->v<<endl;;		
			pop();			//测试pop()函数
		}
	}
	for(i=1;i<=3;i++)
	{
		cin>>m;
		push(m);
	}clear();			//测试clear()函数
	if(empty())				//测试empty()函数
		cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/shamansi99/article/details/89421395