使用双向链表实现队列

队列是常见的数据结构,特点是:从头删除,从尾加入。

本文使用双向链表实现队列,具体代码如下:

 1 #include<stdlib.h>
#inlcude<stdio.h> 2 #define new(type) (type*)malloc(sizeof(type)) 3 typedef struct ListNode{ 4 int data; 5 struct ListNode *lLink; 6 struct ListNode *rLink; 7 }Queue; 8 Queue* Insert(Queue *tail,int x){ 9 Queue* ptr = new(Queue); 10 ptr->data = x; 11 if(tail == NULL){ 12 ptr->lLink = ptr->rLink = NULL; 13 tail = ptr; 14 } 15 else{ 16 ptr->lLink = tail; 17 tail->rLink = ptr; 18 ptr->rLink = NULL; 19 tail = ptr; 20 } 21 return tail; 22 } 23 Queue* Delete(Queue *head){ 24 Queue* temp = head; 25 head = head->rLink; 26 head->lLink = NULL; 27 free(temp); 28 return head; 29 } 30 //flag==0,print from head 31 //flag==1,print from tail 32 void print(Queue *head,Queue *tail,int flag){ 33 Queue* temp; 34 if(flag == 0){ 35 printf("\nHEAD--->TAIL:"); 36 temp = head; 37 while(temp != NULL){ 38 printf("%d,",temp->data); 39 temp = temp->rLink; 40 } 41 } 42 else if(flag == 1){ 43 printf("\nTAIL--->HEAD:"); 44 temp = tail; 45 while(temp != NULL){ 46 printf("%d,",temp->data); 47 temp = temp->lLink; 48 } 49 } 50 else 51 printf("Wrong input,flag should be 0 or 1\n"); 52 } 53 int main(){ 54 Queue *head,*tail; 55 head = NULL; 56 tail = NULL; 57 int i; 58 printf("Create the queue\n"); 59 for(i = 0; i < 5; i++){ 60 Queue *ptr = new(Queue); 61 ptr->data = i; 62 if(head == NULL && tail == NULL){ 63 ptr->lLink = NULL; 64 ptr->rLink = NULL; 65 head = ptr; 66 tail = ptr; 67 } 68 else{ 69 ptr->lLink = tail; 70 tail->rLink = ptr; 71 ptr->rLink = NULL; 72 tail = ptr; 73 } 74 } 75 print(head,tail,0); 76 print(head,tail,1); 77 tail = Insert(tail,5); 78 head = Delete(head); 79 print(head,tail,0); 80 print(head,tail,1); 81 return 0; 82 }

运行结果如下:

这里需要注意的问题就是Delete()和Insert()函数,最开始我是直接传入的head和tail,然后以为修改后head和tail就跟着改变,

但是不是的,需要将其返回重新赋值才行。所以重新将其返回值定义为Queue*。

posted on 2013-04-29 19:09  Licious  阅读(490)  评论(0编辑  收藏  举报