#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Elemtype;
typedef int Status;
/*队列结点的结构体*/
typedef struct _QNode
{
Elemtype data;
struct _QNode* pNext;
}QNode;
/*队列指针*/
typedef struct _myQueue
{
QNode* front;//QNode*类型的队头指针,用以指向队头结点
QNode* rear;//QNode*类型的队尾指针,用以指向队尾的结点
}myQueue;
/*队列初始化*/
Status initQueue(myQueue* queue)
{
queue->front=(QNode*)malloc(sizeof(_QNode));//先为队头分配一个结点大小的内存
if (!queue->front)
{
return ERROR;
}
//要注意头指针指向的节点只存放下一结点的地址,不存放数据
queue->rear = queue->front;//队头指针与队尾指针指向同一个内存
queue->front->pNext = NULL;//队列头指针指向的地址初始化为空
return OK;
}
/*销毁队列*/
Status destroyQueue(myQueue* queue)
{
QNode* ptr;
while(queue->front)//当队尾的指针域(指向NULL)赋给头指针时结束循环
{
ptr = queue->front->pNext;//记录本结点的指针域
free(queue->front);//销毁本结点
queue->front = ptr;//指针域指向的下一结点
}
return OK;
}
/*清空队列*/
Status clearQueue(myQueue* queue)
{
destroyQueue(queue);
initQueue(queue);
return OK;
}
/*判断队列是否为空*/
Status isEmpty(const myQueue* queue)
{
if (queue->front->pNext == NULL)
{
return TRUE;
}
else
{
return FALSE;
}
}
/*获取队列长度*/
int getLength(myQueue queue)//不能传指针,因为不能对原有队列进行修改
{
int count = 0;
QNode* ptr = queue.front->pNext;
while (ptr)
{
++count;
ptr = ptr->pNext;
}
return count;
}
/*获取队列的头元素*/
//头指针指向的结点没有存放数据!
Elemtype getHead(const myQueue* queue)
{
if (NULL == queue->front->pNext)
//if(queue->front==queue->rear)
{
return ERROR;
}
return queue->front->pNext->data;
}
/*入队*/
Status intoQueue(myQueue* queue,Elemtype target)
{
QNode* newNode = (QNode*)malloc(sizeof(_QNode));//创建新结点
if (!newNode)
{
return ERROR;
}
newNode->data = target;
newNode->pNext = NULL;//从队尾插入,并且队尾的结点的指针域一定指向空
queue->rear->pNext = newNode;
queue->rear = newNode;//队尾指针指向新的结点
return OK;
}
/*出队*/
Elemtype outQueue(myQueue* queue)
{
Elemtype returnElem;
if (NULL == queue->front->pNext)
{
return ERROR;
}
QNode* ptr = queue->front->pNext;
returnElem = ptr->data;
queue->front->pNext = ptr->pNext;
//如果有三个结点,那么队尾指针没有改变
if (ptr == queue->rear)//但是如果只有两个结点,删除掉了第二个结点后,队尾指针须要改变了!
{
queue->rear = queue->front;
}
free(ptr);
return returnElem;
}
/*遍历队列*/
Status traverseQueue(myQueue queue)
{
if (queue.front->pNext = NULL)//如果队列为空
{
return ERROR;
}
else
{
QNode* ptr = queue.front->pNext;
while (ptr)
{
printf("%d ", ptr->data);
ptr = ptr->pNext;
}
return OK;
}
}
/*测试主函数*/
int main()
{
myQueue queue;
if (initQueue(&queue))
{
printf("init success\n");
}
if (isEmpty(&queue))
{
printf("queue is empty\n");
}
for (int i = 0; i < 10; i++)
{
intoQueue(&queue, i);
}
printf("the value of this queue's head is %d\n", getHead(&queue));
printf("the length of this queue is %d\n",getLength(queue));
printf("now the value been delete from queue is %d\n", outQueue(&queue));
traverseQueue(queue);
if (destroyQueue(&queue))
{
printf("destroy queue success\n");
}
printf("%p", queue.front);
return 0;
}
队列(链式结构)的实现
猜你喜欢
转载自blog.csdn.net/qq_35042020/article/details/52719889
今日推荐
周排行