循环顺序队列与链式队列实现

队列是一种先进先出的数据结构,分顺序存储结构和链式存储结构两种。顺序存储结构中广泛使用的是循环队列,也是队列使用中最多的一种。下面将分别实现这两种队列的基本操作。

#include
using namespace std;
const int MaxSize = 100;
class queue
{
public:
	queue()
	{
		front = 0;
		rear = 0;
	}
	int isEmpty();
	int enqueue(int x);
	int dequeue();
	void printqueue();
	int lengthqueue();

protected:
private:
	int data[MaxSize];
	int front;
	int rear;
};

int queue::isEmpty()
{
	if (front == rear)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int queue:: enqueue(int x)
{
	if ((rear + 1) % MaxSize == front)
	{
		cout << "队列满" << endl;
		return 0;
	}
	data[rear] = x;
	rear = (rear + 1) % MaxSize;
	return 1;
}

int queue::dequeue()
{
	int x;
	if (isEmpty())
	{
		cout << "队列空" << endl;
		//return 0;
	}
	else
	{
		x = data[front];
		front = (front + 1) % MaxSize;
		return x;
	}
}

int queue::lengthqueue()
{	
	return ((rear - front + MaxSize) % MaxSize);
}

void queue::printqueue()
{
	for (int i = front; i < front+lengthqueue(); i = (i + 1) % MaxSize)
	{		
		cout << data[i] << endl;
	}
}

#include
using namespace std;
class Node
{
public:
	Node(int x)
	{
		data = x;
		next = NULL;
	}
	int data;
	Node *next;
};
class queue
{
public:
	queue()
	{
		front = NULL;
		rear = NULL;
	}
	int isEmpty();
	void enqueue(int x);
	int dequeue();
	int lengthqueue();
	void printqueue();
private:
	Node *front;
	Node *rear;
	int length = 0;
};

int queue::isEmpty()
{
	if (front == NULL)
	{
		return 1;
	}
	else 
	{
		return 0;
	}
}

void queue::enqueue(int x)
{
	Node *temp = new Node(x);
	if (isEmpty() == 1)
	{
		front = rear = temp;
	}
	else
	{
		rear->next = temp;
		rear = temp;
	}
}
int queue::dequeue()
{
	if (isEmpty() == 1)
	{
		cout << "队列为空" << endl;
		return -1;
	}
	else
	{
		Node *temp = front;
		front = front->next;
		return temp->data;
	}
}
void queue::printqueue()
{
	Node *p = front;
	while (p != NULL)
	{
		cout << p->data;
		cout << " ";
		p = p->next;	
	}
	cout << endl;
}

int queue::lengthqueue()
{
	Node *p=front;
	while (p!=NULL)
	{
		length++;
		p = p->next;
	}
	return length;
}

 

 

你可能感兴趣的:(个人历程,代码)