【队列】用c++链表实现队列

#include 
using namespace std;

class Node
{
public:
	double data;
	Node* next;

	Node()
	{
		next = nullptr;
	}
};


class Queue
{
public:
	Queue();
	~Queue();
	bool IsEmpty(void);
	void Enqueue(double x);
	bool Dequeue(double& x);
	void DisplayQueue(void);

private:
	Node* front;
	Node* rear;
	int count;
};

Queue::Queue()
{
	front = rear = NULL;
	count = 0;
}

Queue::~Queue()
{
	Node* temp = nullptr;
	while (count--)
	{
		temp = front;
		front = front->next;
		delete temp;
	}
}

bool Queue::IsEmpty()
{
	if (count)
		return false;
	else
		return true;
}

void Queue::Enqueue(double x)
{
	Node* temp = new Node;
	temp->data = x;
	if (IsEmpty())
	{
		front = temp;
		rear = temp;
	}
	else
	{
		rear->next = temp;
		rear = temp;
	}
	count++;
}

bool Queue::Dequeue(double& x)
{
	if (IsEmpty())
	{
		cout << "队列里没有任何元素" << endl;
		return false;
	}
	else
	{
		Node* temp = front->next;
		x = front->data;
		delete front;
		front = temp;
		count--;
	}
}

void Queue::DisplayQueue()
{
	Node* temp = front;
	if (IsEmpty())
	{
		cout << "队列结构是空的" << endl;
		return;
	}
	for (int i = 0; i < this->count; i++)
	{
		cout <data << " ";
		temp = temp->next;
	}
	cout << endl;
}

int main()
{
	Queue my_queue;
	for (int i = 0; i < 5; i++)
	{
		my_queue.Enqueue(i);
	}
	my_queue.DisplayQueue();
	double x;
	my_queue.Dequeue(x);
	cout << "出列了 " << x << endl;
	my_queue.DisplayQueue();
	return 0;
}

你可能感兴趣的:(算法与数据结构,c++,链表,算法,队列)