具体操作如下:
/*
* queue.c
*
* Created on: 2010-12-21
* Author: qiang
*/
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_INIT_SIZE 5
typedef int QElemType;
typedef int Status;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode;
typedef struct{
QNode *front; //队头
QNode *rear; //队尾
}SqQueue;
//队列初始化
Status Init(SqQueue* Q)
{
Q->front = Q->rear =NULL; //队列的头尾置空
return 0;
}
//添加数据入队
Status QueueInsert(SqQueue *Q,QElemType e)
{
QNode *node; //定义新节点
node = (QNode*)malloc(sizeof(QNode));
if(node == NULL)
printf("err:内存分配失败!\n");
printf("mem of data: %p H \n",node);
//节点赋值
node->next = NULL; //声明为尾节点
node->data = e;
//
if(Q->rear == NULL)
Q->front = Q->rear = node; //队列只有一个节点
else
{
Q->rear->next = node;
Q->rear = Q->rear->next;
printf("rear data:%d \n",Q->rear->data);
}
return 0;
}
//取出队头节点
Status DeQueue(SqQueue *Q,QElemType *e)
{
if(Q->rear == Q->front)
{
printf("队列为空! \n");
}
else
{
QNode *tmpNode;
tmpNode = Q->front;
(*e) = tmpNode->data;
Q->front = tmpNode->next;
//判断取出数据后是否为空
if(tmpNode == Q->rear)
{
Q->front = Q->rear;
}
free(tmpNode); //释放队头内存
}
return 0;
}
//销毁队列
Status DestroyQueue(SqQueue *Q)
{
QNode *curNode;
curNode = Q->front; //指向头节点
if(curNode)
{
Q->front = Q->front->next;
free(curNode); //释放节点内存
curNode = Q->front;
}
Q->rear = Q->front = NULL; //头尾置空
return 0;
}
//判断队列是否为空
int QueueEmpty(SqQueue *Q)
{
//判断队首或队尾任一个指针是否为空即可
if(Q->front==NULL)
return 1;
else
return 0;
}
Status GetHead(SqQueue *Q,QElemType *e)
{
if(Q->front == NULL)
{
printf("Queue is Empty,GetHead error! \n");
return -1;
}
else
{
(*e) = Q->front->data;
return 0;
}
return 0;
}
//获取队列的长度-元素的个数
int QueueLength(SqQueue *Q)
{
int n = 0; //注意n的初始化
QNode *curNode;
curNode = Q->front;
while(curNode)
{
curNode = curNode->next;
n++;
}
return n;
}
int main()
{
SqQueue Q;
//初始化一个队列
if(Init(&Q)!=0)
{
printf("Init error! \n");
return -1;
}
printf("Init OK! \n");
//插入x到队列中
int x;
printf("请输入插入队列的数据:\n");
while(scanf("%d",&x)!=EOF)
{
printf("Insert data: %d \n",x);
QueueInsert(&Q,x);
}
//打印队列中的数据
QNode *curNode;
curNode = Q.front;
printf("队列中的数据为: \n");
while(curNode!=NULL)
{
printf("addr: %p H ;queue data: %d \n",curNode,curNode->data);
curNode = curNode->next;
}
//获得队列长度-元素的个数
int i;
i = QueueLength(&Q);
printf("Length is %d \n",i);
//读取队列头元素
int j;
if(!GetHead(&Q,&j))
{
printf("Head data: %d \n",j);
}
//删除队列所有元素
if(DestroyQueue(&Q)==0)
printf("DestroyQueue OK! \n");
//判断是否为空
if(QueueEmpty(&Q))
printf("Queue is empty! \n");
return 0;
}
|
结果:
qiang@LinuxSir:~/workspace/queue/Debug$ ./queue
Init OK!
请输入插入队列的数据:
1
Insert data: 1
mem of data: 0x9705008 H
2
Insert data: 2
mem of data: 0x9705018 H
rear data:2
3
Insert data: 3
mem of data: 0x9705028 H
rear data:3
队列中的数据为:
addr: 0x9705008 H ;queue data: 1
addr: 0x9705018 H ;queue data: 2
addr: 0x9705028 H ;queue data: 3
Length is 3
Head data: 1
DestroyQueue OK!
Queue is empty!
|
文件: | queue.zip |
大小: | 27KB |
下载: | 下载 |
|
阅读(465) | 评论(0) | 转发(0) |