《鏈?zhǔn)疥?duì)列的基本操作.doc》由會員分享,可在線閱讀,更多相關(guān)《鏈?zhǔn)疥?duì)列的基本操作.doc(4頁珍藏版)》請?jiān)谘b配圖網(wǎng)上搜索。
#include
#include
typedef char ElemType;
typedef struct QNode
{
ElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;//鏈?zhǔn)疥?duì)列
//初始化
LinkQueue InitQueue()
{
LinkQueue Q;
Q.rear=(QNode *)malloc(sizeof(QNode));
Q.front =Q.rear;
if(Q.front ==NULL) printf("內(nèi)存分配失敗\n");
else {Q.front->next=NULL;return Q;}
}
//判斷鏈棧是否為空
int QueueEmpty(LinkQueue Q)
{
if(Q.front->next==NULL) return 1;
else return 0;
}
//求鏈?zhǔn)疥?duì)列長度
int QueueLength(LinkQueue Q)
{
int count=0;
QNode *s;
s=Q.front->next ;
while(s!=NULL)
{
count++;
s=s->next ;
}
return count;
}
//元素入隊(duì)
int EnQueue(LinkQueue &Q,ElemType e)
{
QNode *s;
s=(QNode *)malloc(sizeof(QNode));
if(!s) {printf("內(nèi)存分配失敗\n");return 0;}
else
{
s->data =e;
s->next =NULL;
Q.rear->next =s;
Q.rear =s;
return 1;
}
}
//元素出隊(duì)
int DeQueue(LinkQueue &Q,ElemType &e)
{
QNode *s;
if(Q.front==Q.rear)
{
printf("隊(duì)列已空\n");
return 0;
}
else
{
s=Q.front->next ;
e=s->data ;
Q.front->next =s->next ;
if(Q.rear==s) Q.rear =Q.front ;
free(s);
return 1;
}
}
//取隊(duì)頭元素
int GetHead(LinkQueue Q,ElemType &e)
{
QNode *s;
if(Q.front ==Q.rear ){printf("隊(duì)列已空\n");return 0;}
else
{
s=Q.front->next;
e=s->data ;
return 1;
}
}
//清空隊(duì)列
void ClearQueue(LinkQueue &Q)
{
while(Q.front !=NULL )
{
Q.rear =Q.front->next ;
free(Q.front );
Q.front =Q.rear;
}
}
//遍歷隊(duì)列
void QueueTraverse(LinkQueue Q)
{
QNode *s;
ElemType e;
s=Q.front->next ;
while(s)
{
e=s->data;
printf("%c ",e);
s=s->next;
}
}
int scan()
{
int d;
printf("\n\n\n\n請輸入要進(jìn)行的操作\n1.初始化一個鏈?zhǔn)疥?duì)列\(zhòng)n2.清空隊(duì)列\(zhòng)n3.求隊(duì)列長度\n4.檢查隊(duì)列是否為空\n5.取隊(duì)頭元素\n6.元素入隊(duì)\n7.元素出隊(duì)\n8.輸出隊(duì)列所有元素\n其他鍵退出...\n");
scanf("%d",&d);
return (d);
}
int main()
{
int quit=0;
ElemType e;
LinkQueue Q;
while(!quit)
switch(scan())
{
case 1:Q=InitQueue();printf("\n");break;
case 2:ClearQueue(Q);printf("\n");break;
case 3:printf("隊(duì)列的長度為:%d\n",QueueLength(Q));break;
case 4:if(QueueEmpty(Q))printf("隊(duì)列為空\n");else printf("隊(duì)列非空\n");break;
case 5:if(GetHead(Q,e)) printf("隊(duì)頭元素為:%c",e);else break;break;
case 6:printf("請輸入要入隊(duì)的元素:");getchar();scanf("%c",&e);if(EnQueue(Q,e)) printf("%c已入隊(duì)\n",e);break;
case 7:if(DeQueue(Q,e)) printf("%c已出隊(duì)\n",e);break;
case 8:QueueTraverse(Q);break;
default:quit=1;
}
return 0;
}
鏈接地址:http://www.3dchina-expo.com/p-6692822.html