第九篇:基本数据结构——队列的链式表示
来源:互联网 发布:最优化方法第二版答案 编辑:程序博客网 时间:2024/04/30 05:49
该队列为链式队列,初建队列时,队头和队尾均指向头结点,头结点中不存放数据,只存放指针,头结点的下一个节点才开始存放数据,这这样做的目的是为了在入队和出队时方便对队列的操作,而不用考虑特殊情况。C语言源代码
- #include<stdio.h>
- #include<stdlib.h>
-
- typedef struct Node
- {
- int data;
- struct Node *pNext;
- }NODE,*PNODE;
-
- typedef struct Queue
- {
- PNODE front;
- PNODE rear;
- }QUEUE,*PQUEUE;
-
- PQUEUE create_queue();
- bool is_empty(PQUEUE);
- void en_queue(PQUEUE, int);
- bool de_queue(PQUEUE,int *);
- void destroy_queue(PQUEUE);
- void traverse_queue(PQUEUE);
-
- int main()
- {
- int data_de = 0;
-
-
- PQUEUE pS = create_queue();
- en_queue(pS,2);
- en_queue(pS,4);
- en_queue(pS,6);
- traverse_queue(pS);
-
-
- if(de_queue(pS,&data_de))
- printf("delete succeed,the deleted data is: %d\n",data_de);
- else
- printf("queue is empty! delete falied!\n");
- traverse_queue(pS);
-
-
- destroy_queue(pS);
- printf("queue destroyed!\n");
- traverse_queue(pS);
-
- return 0;
- }
-
-
-
-
-
- PQUEUE create_queue()
- {
- PQUEUE pS = (PQUEUE)malloc(sizeof(Queue));
- pS->front = (PNODE)malloc(sizeof(NODE));
- if(!pS || !pS->front)
- {
- printf("pS or front malloc failed!!");
- exit(-1);
- }
- else
- {
- pS->rear = pS->front;
- pS->front->pNext = NULL;
- }
- return pS;
- }
-
-
-
-
- bool is_empty(PQUEUE pS)
- {
- if(pS->front == pS->rear)
- return true;
- else
- return false;
- }
-
-
-
-
- void en_queue(PQUEUE pS, int e)
- {
- PNODE pNew = (PNODE)malloc(sizeof(NODE));
- if(!pNew)
- {
- printf("pNew malloc failed");
- exit(-1);
- }
- else
- {
- pNew->data = e;
- pNew->pNext = NULL;
- pS->rear->pNext = pNew;
- pS->rear = pNew;
- }
- return;
- }
-
-
-
-
-
- bool de_queue(PQUEUE pS,int *pData)
- {
- if(is_empty(pS))
- return false;
- else
- {
- PNODE p = pS->front->pNext;
- *pData = p->data;
- pS->front->pNext = p->pNext;
-
-
-
-
- if(pS->rear == p)
- pS->rear = pS->front;
- free(p);
- }
- return true;
- }
-
-
-
-
- void traverse_queue(PQUEUE pS)
- {
- if(is_empty(pS))
- printf("there is no data in the queue!\n");
- else
- {
- PNODE pCurrent = pS->front->pNext;
- printf("Now datas int the queue are:\n");
- while(pCurrent)
- {
- printf("%d ",pCurrent->data);
- pCurrent = pCurrent->pNext;
- }
- printf("\n");
- }
- return;
- }
-
-
-
-
- void destroy_queue(PQUEUE pS)
- {
- if(is_empty(pS))
- return;
- else
- {
- while(pS->front)
- {
- pS->rear = pS->front->pNext;
- free(pS->front);
- pS->front = pS->rear;
- }
- }
- free(pS);
- pS = 0;
- return;
- }