您的位置:首页 > 其它

队列的链式存储结构及实现

2016-11-12 13:44 363 查看
队列的链式存储结构其实就是线性表的单链表,只不过它只能尾进头出,也称为链队列。为了操作方便讲队头指针指向链队列的头结点,而队尾指针指向终端节点。



空队列是这样



下面使用代码演示:

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

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

typedef struct Queue
{
PNODE front;
PNODE rear;
}QUEUE,*PQUEUE;

void initQueue(PQUEUE);
bool addQueue(PQUEUE,int);
bool deleteQueue(PQUEUE,int *);
bool isEmpty(PQUEUE);
void showQueue(PQUEUE);
int main(void)
{
QUEUE q;
int m;
initQueue(&q);
addQueue(&q,3);
addQueue(&q,-33);
addQueue(&q,90);
addQueue(&q,35);
showQueue(&q);
deleteQueue(&q,&m);
showQueue(&q);
return 0;
}

void showQueue(PQUEUE pQueue)
{
PNODE p = pQueue->front;
while(p->pNext!=NULL)
{
p=p->pNext;
printf("%d  ",p->data);
}
printf("\n");
}

bool isEmpty(PQUEUE queue)
{
if(queue->front == queue->rear)
{
return true;
}
return false;
}

void initQueue(PQUEUE queue)
{
PNODE p = (PNODE)malloc(sizeof(NODE));
if(p==NULL)
{
printf("动态内存分配失败!\n");
exit(-1);
}
p->pNext = NULL;
queue->front = p;
queue->rear = queue->front;
return;
}

bool addQueue(PQUEUE queue,int e)
{
PNODE p = (PNODE)malloc(sizeof(NODE));
if(p==NULL)
{
printf("动态内存分配失败!\n");
exit(-1);
}
p->data =e;
p->pNext = NULL;
queue->rear->pNext = p;
queue->rear = p;
return true;
}

bool deleteQueue(PQUEUE queue,int * pVal)
{
if(isEmpty(queue))
{
return false;
}
PNODE p = queue->front->pNext;
*pVal = p->data;
printf("删除的结点是:%d\n",*pVal);
if(p==queue->rear)
{
queue->front = queue->rear;
queue->front->pNext = NULL;
}
else
{
queue->front ->pNext = p->pNext;
}
free(p);
p = NULL;
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列 线性表 单链表