Code
/*鏈表實現隊列的一系列操作*/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef struct node
{
int data; //數據域
struct node *next; //指針域
}LinkQueueNode;
typedef struct
{
LinkQueueNode *front; //頭指針
LinkQueueNode *rear; //尾指針
}LinkQueue;
/**********************各個子函數的定義*********************/
void initQueue(LinkQueue *Q); //鏈隊列初始化
int enterQueue(LinkQueue *Q,int n); //鏈隊列入隊操作
void deleteQueue(LinkQueue *Q); //鏈隊列出隊操作
int main()
{
LinkQueue Q;
int choice;
while(true)
{
printf("*****************Please enter your choice*****************\n\n");
printf(" choice 1:Queue initialization\n");
printf(" choice 2:Into the queue\n");
printf(" choice 3:Out of the queue\n");
printf(" choice 0:exit\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
initQueue(&Q);
break;
case 2:
int n;
printf("Please enter the number into the queue elements:");
scanf("%d",&n);
(enterQueue(&Q,n)==1)?printf("%d個元素依次進隊成功\n",n):printf("%d個元素依次進隊失敗\n",n);
break;
case 3:
deleteQueue(&Q);
break;
case 0:
exit(0);
break;
default:
printf("ERROR!!\n");
exit(0);
break;
}
}
return 0;
}
/**********************各個子函數功能的實現*********************/
void initQueue(LinkQueue *Q)
{ //將 Q 初始化為一個空鏈隊列
Q->front=(LinkQueueNode *)malloc(sizeof(LinkQueueNode));
Q->rear=Q->front;
Q->front->next=NULL;
}
int enterQueue(LinkQueue *Q,int n) //進隊列
{
LinkQueueNode *temp;
int n1,n2;
printf("Please enter into the queue elements in turn:\n");
for(n1=0;n1<n;n1++)
{
scanf("%d",&n2);
temp=(LinkQueueNode *)malloc(sizeof(LinkQueueNode));
if(temp==NULL) return ERROR; //申請空間失敗
temp->data=n2;
temp->next=NULL;
Q->rear->next=temp;
Q->rear=temp; //隊尾指針后移
}
return OK;
}
void deleteQueue(LinkQueue *Q)
{
int a;
LinkQueueNode *temp;
if(Q->front==Q->rear) //隊為空,出棧失敗
{
printf("An empty Queue error!!!!\n");
}
else
{
temp=Q->front->next;
a=temp->data;
Q->front->next=temp->next;
if(Q->front==temp) //如果隊中只有一個元素X,則X出隊后成為空隊
{
Q->rear=Q->front;
}
free(temp); //釋放存儲空間
printf("隊頂元素%d出隊成功.\n",a);
}
}