您的位置:首页 > 理论基础 > 数据结构算法

队列的链式表示和实现

2015-10-25 18:44 531 查看
用链表表示的队列简称为链队列。一个链队列显然需要两个分别指示队头和队尾的指针(分别称为头指针和尾指针)才能唯一确定。和线性表的单链表一样,为了操作方便起见,我们也给链队列添加一个头结点,并令头指针指向头结点。由此,空的链队列的判断条件为头指针和尾指针均指向头结点,如图所示//- - - - - - - - - -单链队列——队列的链式存储结构- - - - - - - - -
typedef struct QNode{
int date;
struct QNode *next;
}QNode,*QueuePtr;

typedef struct{
QueuePtr Front;   //队头指针
QueuePtr rear;    //队尾指针
}LinkQueue;
//InitQueue
//构造一个空队列Q
int InitQueue(LinkQueue &Q){
Q.Front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q.Front)
exit(OVERFLOW);
Q.Front->next=NULL;
return OK;
}
//DestoryQueue
//销毁队列Q
int DestoryQueue(LinkQueue &Q){
while(Q.Front){
Q.rear=Q.Front->next;
free(Q.Front);
Q.Front=Q.rear;
}
return OK;
}
//EnQueue
//插入元素e为Q的新的队尾元素
int EnQueue(LinkQueue &Q,int e){
QNode *p;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p)
exit(OVERFLOW);
p->date=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;
}
//Dequeue//删除Q的队头元素,用e返回其值int DeQueue(LinkQueue &Q,int &e){if(Q.Front==Q.rear)return ERROR;QNode *p;p=Q.Front->next;e=p->date;Q.Front->next=p->next;if(Q.rear==p)Q.rear=Q.Front;free(p);return OK;}//QueueLength//返回队列的长度int QueueLength(LinkQueue Q){QNode *p;p=Q.Front;int i=0;while(p!=Q.rear){p=p->next;i++;}return i;}//QueueTraverse//遍历队列Qint QueueTraverse(LinkQueue Q){int l=QueueLength(Q);for(int i=0;i<l;i++){Q.Front=Q.Front->next;printf("%d ",Q.Front->date);}printf("\n");}//main<pre name="code" class="cpp">int main(){LinkQueue Q;InitQueue(Q);int e;printf("Please input elem:\n");while(~scanf("%d",&e)){EnQueue(Q,e);}printf("Output:\n");QueueTraverse(Q);}
//结果预览
 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 链队列