1. 程式人生 > >C++用陣列實現一個固定大小的棧/佇列

C++用陣列實現一個固定大小的棧/佇列

#include<iostream>
#include<exception>
using namespace std;
#define NUM 5
//用陣列結構實現大小固定的佇列和棧
class ArrayIndexOutOfBoundsException:public exception
{
private:
	const char*ptr;
public:
	ArrayIndexOutOfBoundsException(const char*ptr)
	{
		this->ptr = ptr;
	}
	virtual char const *what()
	{
		cout<<this->ptr<<endl;
		return ptr;
	}
};
class MyStack
{
private:
	int *array;
	int idx;
	int N;
public:
	MyStack(int N);
	~MyStack();
	void push(int element);
	int pop();
	int peek();
	void printStack();
	
};
MyStack::MyStack(int N)
{
	this->N = N;
	array = new int[N];
	idx=0;
	
}
MyStack::~MyStack()
{
	delete[] this->array;
}
void MyStack::push(int element)
{
	if(idx == N)
		throw ArrayIndexOutOfBoundsException("棧已滿");
	else
		array[idx++] = element;
}
int MyStack::pop()
{
	if(idx == 0)
		throw ArrayIndexOutOfBoundsException("棧中無元素");
	else
		return array[--idx];
}
int MyStack::peek()
{
	if(idx == 0)
	{
		return -1;
	}
	else
		return array[idx-1];//注意這裡是看棧頂元素,但並不把元素去除所以用idx-1而不用--idx;
		
}
void MyStack::printStack()
{
	for(int i=0;i<N;i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
}


int main()
{
	MyStack stack1(NUM);
	stack1.push(1);
	stack1.push(2);
	stack1.push(3);
	stack1.push(4);
	stack1.push(15);
	stack1.printStack();
	for(int i=0;i<NUM;i++)
	{
		cout<<"pop = "<<stack1.pop()<<endl;
		cout<<"peek = "<<stack1.peek()<<endl;
		cout<<endl;
	}
	stack1.printStack();
	return 0;
}

棧的實現相對簡單,佇列複雜一點。

#include<iostream>
#include<exception>
using namespace std;
#define NUM 5
//用陣列結構實現大小固定的佇列和棧
class ArrayIndexOutOfBoundsException:public exception
{
private:
	const char*ptr;
public:
	ArrayIndexOutOfBoundsException(const char*ptr)
	{
		this->ptr = ptr;
	}
	virtual char const *what()
	{
		cout<<this->ptr<<endl;
		return ptr;
	}
};
class MyQuene
{
private:
	int *array;
	int start;
	int end;
	int size;
	int len;
public:
	MyQuene(int N);
	~MyQuene();
	void push(int);
	int poll();
	int peek();
};

MyQuene::MyQuene(int N)
{
	size = 0;
	start =0;
	end = 0;
	len = N;
	array = new int[len];
}

MyQuene::~MyQuene()
{
	delete[] array;
}

void MyQuene::push(int element)
{
	if(end == len)
		throw new ArrayIndexOutOfBoundsException("The qunen is full");
	size++;
	array[end] = element;
	end = end == len -1 ? 0 : end+1;
}
int MyQuene::poll()
{
	if(size == 0)
		throw new ArrayIndexOutOfBoundsException("The qunen is empty");
	size--;
	int tmp = start;
	start = start == len-1 ? 0 : start +1;
}
int MyQuene::peek()
{
	if(size == 0)
	{
		cout<<"The qunen is empty"<<endl;
		return -1;
	}

	return array[start];
}

int main()
{
	MyQuene myQ(NUM);
	myQ.push(1);
	myQ.poll();
	myQ.peek();
	return 0;
}