數據結構的C實現_鏈式隊列

//編譯環境 visual studio 2008,win32 console application.

//LinkQueue.c

//帶頭節點的鏈式隊列
#include <stdio.h>
#include <stdlib.h>
#define    OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char elemType;//元素類型

typedef struct _QNode
{
elemType data;
struct _QNode *next;
}QNode;//節點類型

typedef struct
{
QNode *front;//
QNode *rear;
}LinkQueue;//隊列類型

//初始化隊列
int InitQueue(LinkQueue *q)
{
q->front=q->rear=(QNode *)malloc(sizeof(QNode));
if(!q->front) exit(OVERFLOW);
q->front->next=NULL;
return OK;
}
//銷燬隊列
int DestroyQueue(LinkQueue *q)
{
while(q->front)
{
q->rear=q->front->next;
free(q->front);
q->front=q->rear;
}
return OK;
}
//隊尾插入元素e
int EnQueue(LinkQueue *q,elemType e)
{
QNode *p=(QNode *)malloc(sizeof(QNode));
if(!p) exit(OVERFLOW);
p->data=e;
p->next=NULL;
q->rear->next=p;
q->rear=p;
return OK;
}
//刪除隊頭元素,並打印其值
int DeQueue(LinkQueue *q)
{
QNode *p=q->front->next;//因爲帶頭節點,所以隊頭是頭節點的後一個元素
if(q->front==q->rear) return ERROR;
printf("已刪除隊頭元素%c\n",p->data);
q->front->next=p->next;
if(q->rear==p) q->rear=q->front;
free(p);
return OK;
}
//遍歷隊列
void TraverseQueue(LinkQueue *q)
{
QNode *p=q->front->next;
if(q->front==q->rear)
printf("隊列爲空\n");
else
{
printf("隊列中的元素爲:\n");
while(p!=q->rear)
{
printf(" %c",p->data);
p=p->next;
}
printf(" %c",q->rear->data);
printf("\n");
}
}

void main()
{
LinkQueue *q=(LinkQueue *)malloc(sizeof(LinkQueue));
InitQueue(q);
TraverseQueue(q);
printf("隊尾插入元素.....\n");
EnQueue(q,'a');
EnQueue(q,'b');
EnQueue(q,'c');
EnQueue(q,'d');
TraverseQueue(q);
printf("刪除隊首元素...\n");
DeQueue(q);
TraverseQueue(q);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章