数据结构之链队列

来源:互联网 发布:实用的防身武术 知乎 编辑:程序博客网 时间:2024/05/22 14:03

一、存储结构

//单链队列,队列的链式存储结构typedef struct QNode{int data;struct QNode *next;}QNode;typedef struct{QNode *front;QNode *rear;}LinkQueue;
示意图:

二、基本操作

1、初始化队列

int InitQueue(LinkQueue &Q){Q.front = Q.rear = (QNode *)malloc(sizeof(QNode));if(!Q.front)return 0;Q.front->next = NULL;return 1;}

2、销毁队列

void DestoryQueue(LinkQueue &Q){while (Q.front){Q.rear = Q.front->next;free(Q.front);Q.front = Q.rear;}}

3、清空队列

void ClearQueue(LinkQueue &Q){QNode *p, *q;//if (Q.front == Q.rear)//return;p = Q.front->next;while(p){q = p->next;free(p);p = q;}Q.front->next = NULL;Q.rear = Q.front;}

4、求队列长度

int QueueLength(LinkQueue Q){int length = 0;QNode *p = Q.front->next;while(p/* != Q.rear->next*/){length++;p = p->next;}return length;}

5、入队列

int EnQueue(LinkQueue &Q, int e){QNode*p = (QNode*)malloc(sizeof(QNode));if(!p)return 0;p->data = e;p->next = NULL;Q.rear->next = p;Q.rear = p;return 1;}

6、出队列

int DeQueue(LinkQueue &Q, int &e){QNode *p;if(Q.front == Q.rear)return 0;p = Q.front->next;e = p->data;Q.front->next = p->next;//一般情况下、删除队列元素时仅需要修改头结点中的指针。//但当队列中的最后一个元素被删除是,队列尾指针也就丢失了、incident需要对队尾指针重新赋值(指向头结点)if(Q.rear == p)Q.rear = Q.front;free(p);return 1;}

7、遍历队列

void QueueTraverse(LinkQueue Q){QNode*p = Q.front->next;while(p/* != Q.rear->next*/){printf("%d ", p->data);p = p->next;}putchar('\n');}
完整测试代码:http://download.csdn.net/detail/u013071074/7424451

0 0
原创粉丝点击