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

队列


简单的实现了push pop empty size;

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

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


【测试代码】

#include <cstdio>
#include<iostream>
#include<malloc.h>
using namespace std;
#define MaxSize 100
typedef 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;
}



posted @ 2015-08-09 16:57  编程菌  阅读(188)  评论(0编辑  收藏  举报