队列的基本操作
#include "stdafx.h"
#include<iostream>
using namespace std;
typedef struct node
{
char data;
struct node *link;//指向后缀结点的指针
};
typedef struct Queue
{
node *first,*rear;//定义队列的头和尾指针
};
Queue * InsertQueue(Queue *Q,char value)
{
node*newNode=(node*)malloc(sizeof(node));
newNode->data=value;
newNode->link=NULL;
if(Q->first==NULL)
Q->first=Q->rear=newNode;
else
{
Q->rear->link=newNode;
Q->rear=newNode;
}
return Q;
}
Queue * DeleteQueue(Queue *Q)
{
node*ptemp;
if(Q->first==NULL)
cout<<"队列已空!"<<endl;
else
{
ptemp=Q->first;
if(Q->first==Q->rear)
{
Q->first=NULL;
Q->rear=NULL;
}
else
Q->first=Q->first->link;
free(ptemp);
}
return Q;
}
Queue * InitQueue()
{
char ch;
node*newNode;
Queue *QL=(Queue*)malloc(sizeof(Queue));//初始化队列
QL->first=(node*)malloc(sizeof(node));//队列中的第一个元素,头尾指针均指向该结点
QL->first->link=NULL;
QL->rear=QL->first;
cout<<"请输入字符串并回车,初始化队列如下:"<<endl;
ch=getchar();
while(ch!='\n')
{
newNode=(node*)malloc(sizeof(node));
newNode->data=ch;
newNode->link=NULL;
if(QL->first==NULL)
QL->first=QL->rear=newNode;
else
{
QL->rear->link=newNode;
QL->rear=newNode;
}
ch=getchar();
}
return QL;
}
int length(Queue *Q)
{
int count=0;
node*ptemp=Q->first;
while(ptemp->link!=NULL)
{
count++;
ptemp=ptemp->link;
}
return count;
}
void DisplayQueue(Queue *QL)
{
node*ptemp;
ptemp=QL->first->link;
if(ptemp==NULL)
cout<<"队列已空!"<<endl;
while(ptemp!=NULL)
{
cout<<ptemp->data;
ptemp=ptemp->link;
if(ptemp!=NULL)
cout<<"——> ";
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Queue *Q=InitQueue();
DisplayQueue(Q);
cout<<"After InsertQueue():"<<endl;
InsertQueue(Q,'c');
cout<<"在队列尾部插入字符c后的元素有:"<<endl;
DisplayQueue(Q);
cout<<"After DeleteQueue():"<<endl;
DeleteQueue(Q);
cout<<"删除队列头部元素后,队列中的元素有:"<<endl;
DisplayQueue(Q);
cout<<"队列中元素的数目是:"<<length(Q)<<endl;
system("pause");
return 0;
}
还没有评论,来说两句吧...