一个简单的队列

#include<iostream>
using namespace std;

struct Node{
	int data;
	Node *next;
	Node(int data, Node* next): data(data), next(next){}
};

class Quene{
private:
	Node *head;
	Node *rear;
	int count;
public:
	Quene(): head(NULL), rear(NULL), count(0){}
	void Push(int to_push);
	int Pop();	
};

void Quene::Push(int to_push){
	Node *new_node = new Node(to_push, NULL);
	if (rear != NULL)
		rear->next = new_node;
	rear = new_node;
	if(count == 0) 
		head = rear;
	++count;	
}

int Quene::Pop(){
	if(count == 0){
		cerr<<"No Element to Pop"<<endl;	
		return -1;
	}
	Node *to_pop = head;
	head = head->next;
	int ret = to_pop->data;
	delete to_pop;
	--count;
	return ret;
}

int main()
{
	Quene my_Quene;
	for(int i=0; i<100; ++i){
		my_Quene.Push(i);
	}
	for(int i=0; i<10; ++i){
		cout<<my_Quene.Pop()<<endl;
	}
	my_Quene.Pop();
	return 0;
}

还是要注意形象思维,先进后出,链式存储,要记住head和rear

弹出的时候从head删除一个

插入的时候从rear插入

原文地址:https://www.cnblogs.com/lovelyxia/p/1946822.html