数据结构学习---队列的链式储存实现

来源:互联网 发布:淘宝店铺层级怎么计算 编辑:程序博客网 时间:2024/04/25 20:05

队列


简单的实现了push pop empty size;

和堆栈的链式实现一样,因为删除操作后需要执向下一个元素,所以队列的删除操作 pop 要在链表的头部实现

因为队列是 First In First Out,所以插入操作 push 要在链表尾插入。


【测试代码】

#include <cstdio>#include<iostream>#include<malloc.h>using namespace std;#define MaxSize 100typedef int ElementType;ElementType ERROR = -1;struct QNode{ ElementType Data;QNode *Next;};class LinkQueue{public:LinkQueue(){//建立新节点,并将储存队列的头、尾指针,指向这一块区域QNode* Q=(QNode*)malloc(sizeof(QNode)); Q->Data=0;Q->Next=NULL;rear=Q;front=Q;}bool empty(){if(front == rear){ //头尾相遇,则队列为空return true;}return false;}int size(){QNode* tmp=front;int sz=0;while(tmp!=rear){ //从“头”走到 “尾” 长度即为队列大小tmp=tmp->Next;sz++;}return sz;}void Push(ElementType X){QNode* LastCell=(QNode*)malloc(sizeof(QNode));LastCell->Data = X;LastCell->Next=NULL; //始终让结尾的Next为空rear->Next = LastCell;//原队尾 的Next赋值为新建立的节点rear=LastCell; //更新队尾}ElementType Pop(){QNode *FrontCell;ElementType FrontElem;//为了输出返回值而创立的临时节点 与变量if(empty()){cout<<"队列空"<<endl; return ERROR;}FrontCell = front; front = front->Next; //头结点始终不存数据,数据在头节点的下一个节点FrontElem = FrontCell->Next->Data;free(FrontCell);return FrontElem;}private:QNode *rear;  //指向队列尾节点QNode *front; //指向队头节点};int main(){LinkQueue Q;Q.Push(4);Q.Push(5);Q.Push(5);cout<<"大小为:"<<Q.size()<<endl;cout<<Q.Pop()<<endl;cout<<Q.Pop()<<endl;cout<<Q.Pop()<<endl;cout<<Q.Pop()<<endl;cout<<"大小为:"<<Q.size()<<endl;return 0;}



1 0
原创粉丝点击