生活随笔
收集整理的這篇文章主要介紹了
链式队列的基本操作(入队、出队、遍历队列、清空队列)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
鏈?zhǔn)疥犃惺且环N特殊的鏈表,只能在尾部添加,在頭部刪除,類似于排隊問題,先入先出
代碼如下
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define ERROR 0
typedef int ElemType
;
typedef struct Queue
{struct Queue
*next
;int data
;
}ListQueue
;
struct Queue
*front
=NULL;
struct Queue
*rear
=NULL;
int length
=0;
ListQueue
*createQueue()
{ListQueue
*s
=(ListQueue
*)malloc(sizeof(ListQueue
));if(!s
){printf("內(nèi)存分配失敗!");exit(ERROR
);}s
->next
=NULL;length
++;return s
;
}
void PushQueue(ListQueue
*s
)
{ListQueue
*p
=(ListQueue
*)malloc(sizeof(ListQueue
));if(!p
) {printf("內(nèi)存分配失敗!");exit(ERROR
); }printf("請輸入你要數(shù)據(jù)的數(shù)據(jù):");int a
;scanf("%d",&a
);p
->data
=a
;p
->next
=NULL;if(length
==1) {front
=rear
=p
;s
->next
=front
;}else {rear
->next
=p
;rear
=p
;}length
++;
}
void PopQueue(ListQueue
*s
)
{if(front
==NULL||rear
==NULL)printf("該隊列已空!");int v
;v
=front
->data
;s
->next
=front
->next
;free(front
);front
=s
->next
;printf("該出隊的數(shù)據(jù)為:");printf("%d",v
);
}
void Display(ListQueue
*s
)
{ListQueue
*v
=s
->next
;while(v
){printf("%d->",v
->data
);v
=v
->next
;}
}
void DestoryQueue(ListQueue
*s
)
{ListQueue
*v
=s
->next
;while(v
){front
=v
->next
;free(v
);v
=front
;}printf("該隊列已清空!");free(s
);printf("\n");printf("頭節(jié)點釋放成功!");
}
int main()
{ListQueue
*t
=createQueue();PushQueue(t
);PushQueue(t
);PushQueue(t
);printf("該數(shù)據(jù)如下");Display(t
);printf("\n");printf("出隊!");PopQueue(t
);printf("\n");printf("余下數(shù)據(jù)如下:");printf("\n");Display(t
);printf("\n");DestoryQueue(t
);return 0;
}
總結(jié)
以上是生活随笔為你收集整理的链式队列的基本操作(入队、出队、遍历队列、清空队列)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。