數據結構學習三:隊列

隊列

     隊列的基本操作有1,:Enqueue(入隊),它是在表的末端即隊尾rear插入一個元素;2:Dequeue(出隊),它是刪除在表頭即隊頭(front)的元素。

#pragma once
#include"node.h"

class MyQueue
{
private:
	Node* m_Head;
	Node* m_Front;
	Node* m_Rear;
public:
	MyQueue();
	~MyQueue();
public:
	bool IsEmpty();
	void Enqueue(int data);
	void Dequeue();
	void ShowQueue();
private:
	void initialize();
};

#include "stdafx.h"
#include "MyQueue.h"


MyQueue::MyQueue()
{
	initialize();
}


MyQueue::~MyQueue()
{
}

bool MyQueue::IsEmpty()
{
	if (m_Front == NULL || m_Rear == NULL || m_Head->Next == NULL)
	{
		return true;
	}
	return false;
}

void MyQueue::Enqueue(int data)
{
	Node* p = new Node();
	p->Data = data;
	p->Next = NULL;
	Node* q = m_Rear;
	q->Next = p;
	m_Rear = p;
	if (q == m_Head)
	{
		m_Front = p;
	}
}

void MyQueue::Dequeue()
{
	if (IsEmpty())
	{
		return;
	}
	Node* p = m_Head;
	Node* q = m_Front;
	p->Next = q->Next;
	m_Front = q->Next;
	delete q;
}

void MyQueue::ShowQueue()
{
	if (IsEmpty())
	{
		cout << "this queue is empty!" << endl;
		return;
	}
	cout << "this queue is (front to rear):" << endl;
	Node* p = m_Front;
	while (p!=NULL)
	{
		cout << p->Data << " ";
		p = p->Next;
	}
	cout << endl;
}

void MyQueue::initialize()
{
	m_Head = new Node();
	m_Head->Next = NULL;
	m_Front = m_Rear = m_Head;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章