队列的C语言实现
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <assert.h> 4 typedef struct node{//定义双向链表节点 5 int data; 6 struct node *pNext; 7 }*pNODE,NODE; 8 typedef struct head{//定义队列头节点 9 pNODE pHead; 10 pNODE pTail; 11 }*pHEAD,HEAD; 12 pHEAD Create(){ 13 pHEAD pHead=NULL; 14 pHead=(pHEAD)malloc(sizeof(HEAD)); 15 assert(pHead); 16 pHead->pHead=NULL; 17 pHead->pTail=NULL; 18 return pHead; 19 } 20 void PutData(pHEAD head,int data){ 21 pNODE pNode=NULL; 22 pNode=(pNODE)malloc(sizeof(NODE)); 23 assert(pNode); 24 pNode->data=data; 25 pNode->pNext=NULL; 26 if (head->pTail)//如果队尾不为空,则让原队尾节点指针指向新节点 27 head->pTail->pNext=pNode; 28 head->pTail=pNode; 29 if(head->pHead==NULL)//当队列为空时,添加新结点后要修改头指针. 30 head->pHead=pNode; 31 } 32 int GetData(pHEAD head){ 33 int data; 34 pNODE pNode=NULL; 35 pNode=head->pHead; 36 assert(pNode); 37 head->pHead=pNode->pNext; 38 data=pNode->data; 39 free(pNode); 40 return data; 41 } 42 int main(){ 43 pHEAD head=NULL; 44 head=Create(); 45 PutData(head,1); 46 PutData(head,2); 47 PutData(head,3); 48 PutData(head,4); 49 printf("%d\t",GetData(head)); 50 printf("%d\t",GetData(head)); 51 printf("%d\t",GetData(head)); 52 printf("%d\t",GetData(head)); 53 }
程序通过在线测试:
http://ideone.com/qXl964