您的位置:首页 > 编程语言 > C语言/C++

链表实现队列 c语言

2015-08-07 18:22 330 查看
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define Data_Type int

typedef struct Node{
Data_Type data;
struct Node * pNext;
}NODE,*PNODE;

typedef struct LinkQueue{
//first node
PNODE front;
//lash node
PNODE rear;
}LINKQUEUE,*PLINKQUEUE;

bool isEmpty(PLINKQUEUE);
bool enQueue(PLINKQUEUE,Data_Type);
Data_Type deQueue(PLINKQUEUE);
void traverse(PLINKQUEUE);
PLINKQUEUE initial();

int main(void){
PLINKQUEUE pLinkQueue = initial();
enQueue(pLinkQueue,1);
enQueue(pLinkQueue,2);
enQueue(pLinkQueue,3);
enQueue(pLinkQueue,4);
deQueue(pLinkQueue);
enQueue(pLinkQueue,5);
deQueue(pLinkQueue);
traverse(pLinkQueue);
return 0;
}

PLINKQUEUE initial(){
PLINKQUEUE pLinkQueue = (PLINKQUEUE)malloc(sizeof(LINKQUEUE));
if(NULL==pLinkQueue){
exit(-1);
}else{
pLinkQueue->front = NULL;
pLinkQueue->rear = NULL;
return pLinkQueue;
}

}

bool isEmpty(PLINKQUEUE pLinkQueue){
if(pLinkQueue->front == NULL && pLinkQueue->rear == NULL){
return true;
}else{
return false;
}
}

bool enQueue(PLINKQUEUE pLinkQueue,Data_Type val){
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL==pNew){
return false;
}
pNew->data = val;
pNew->pNext = NULL;
if(isEmpty(pLinkQueue)){
pLinkQueue->front = pLinkQueue->rear = pNew;
}else{
pLinkQueue->rear->pNext = pNew;
pLinkQueue->rear = pNew;
}
return true;

}

void traverse(PLINKQUEUE pLinkQueue){
PNODE pTemp=pLinkQueue->front;
while(pTemp!=NULL){
printf("%d\n",pTemp->data);
pTemp = pTemp->pNext;
}
}

Data_Type deQueue(PLINKQUEUE pLinkQueue){
PNODE pTemp =pLinkQueue->front;
Data_Type temp;
if(isEmpty(pLinkQueue)){
exit(-1);
}
//The Queue just has one node
if(pLinkQueue->front == pLinkQueue->rear){
pLinkQueue->front = pLinkQueue->rear = NULL;
}else{
pLinkQueue->front=pLinkQueue->front->pNext;
}
temp = pTemp->data;
free(pTemp);
return temp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息