数据结构_队列_用链表动态建立释放节点实现队列各种操作_C++实现

数据结构_队列_用链表动态建立释放节点实现队列各种操作_C++实现

mqueue.h

#include<iostream>
using namespace std;

class NODE
{
public:
	NODE();
	int num;
	NODE *next;
};

NODE::NODE()
{
	num = 0;
	next = NULL;
}

class QUEUE
{
public:
	QUEUE();
	void Push();
	void Pop();
	void Front();
	void Length();
private:
	NODE *front, *rear, *keep;
	int len;
};

QUEUE::QUEUE()
{
	keep = front = rear = NULL;
	len = 0;
}

void QUEUE::Pop()
{
	cout << "Pop Called !" << endl << endl;
	if (front == rear)
	{
		if (front == NULL)
			cout << "Queue Empty !" << endl << endl;
		else
		{
			delete front;
			front = rear = NULL;
			len--;
		}
	}
	else
	{
		keep = front->next;
		delete front;
		front = keep;
		len--;
	}
}

void QUEUE::Push()
{
	cout << "Push Called !" << endl << endl;
	int num;
	cout << "Please Input The Number You Want To Push In This Queue :" << endl
			<< endl;
	cin >> num;
	if (rear == NULL)
		front = rear = new NODE;
	else
	{
		rear->next = new NODE;
		rear = rear->next;
	}
	rear->num = num;
	len++;
}

void QUEUE::Front()
{
	cout << "Front Called !" << endl << endl;
	if (front == NULL)
	{
		cout << "Queue Empty !" << endl << endl;
		return;
	}
	cout << "The Element At The Top Of The Queue Is : " << front->num << endl
			<< endl;
}

void QUEUE::Length()
{
	cout << "The Length Of This Queue Is : " << len << endl << endl;
}

main.cpp

#include<iostream>
#include"mqueue.h"
using namespace std;

int main()
{
	QUEUE q;
	char choice;
	while (1)
	{
		cout << "Your Choice , Please :" << endl << endl << "1 . Push" << endl
				<< "2 . Pop" << endl << "3 . Length" << endl << "4 . Front"
				<< endl << endl;
		cin >> choice;
		switch (choice)
		{
		case '1':
			q.Push();
			break;
		case '2':
			q.Pop();
			break;
		case '3':
			q.Length();
			break;
		case '4':
			q.Front();
			break;
		default:
			cout << "Please Input The Right Choice As Shown Above !" << endl
					<< endl;
			break;
		}
	}
}

发表回复