1. 程式人生 > >資料結構--3.3棧的實現

資料結構--3.3棧的實現

基本操作:入棧、出棧相當於插入、刪除 實現方式:連結串列、陣列。 連結串列:可以通過繼承連結串列來實現。本文略 陣列實現:避免了指標,更流行,唯一的潛在危害是需要提前宣告一個數組的大小,但是在典型的應用中,任一時刻棧元素的個數不會太大,所以此危害可忽略。

#include <iostream>
using namespace std;
/**********************************************************************
棧基本操作
用連結串列實現的棧結構的缺點是總是需要動態的分配資源,如果想解決這個問題可以
用另一個棧結構儲存被刪除的資料,而使用陣列實現則效率更高一些,唯一的不足
就是就是需要提前的申請空間大小,這裡只是實現了一些棧簡答操作。
增加了find_min操作。
**********************************************************************/

typedef struct StackRecord
{
	int m_capcity;//棧容量
	int m_topIndex;//棧頂索引,空棧為-1
	int* m_pArray;//存放棧元素的陣列
} *Stack;

Stack CreatStack(int capacity);//建立空棧
void push(Stack s, int x);
void pop(Stack s);
int top(Stack s);
void MakeEmpty(Stack s);
bool IsDisposeStack(Stack s);//釋放棧
bool IsFull(Stack s);
bool IsEmpty(Stack s);
void Traverse(Stack s);//從棧頂到棧低遍歷
int main()
{
	Stack s = CreatStack(5);
	push(s, 5);
	push(s, 19);
	push(s, 10);
	Traverse(s);
	cout << "一次出棧" << endl;
	pop(s);
	Traverse(s);
	int sTop = top(s);
	cout << "棧頂元素:" << top << endl;
	cout << "置空棧:";
	MakeEmpty(s);
	Traverse(s);
	if (IsDisposeStack(s))
		cout << "釋放成功" << endl;
	else
		cout << "釋放不成功" << endl;
	system("pause");
	return 0;
}


Stack CreatStack(int capacity)
{
	if (capacity < 0)
		cout << "棧太小" << endl;
	Stack stack = new StackRecord;
	stack->m_capcity = capacity;
	stack->m_pArray = new int[capacity];
	MakeEmpty(stack);
	return stack;
}

void push(Stack s, int x)
{
	if (!IsFull(s))
	{
		s->m_topIndex += 1;
		s->m_pArray[s->m_topIndex] = x;
	}
	else
		cout << "棧已滿,入棧失敗" << endl;
}

void pop(Stack s)
{
	if (!IsEmpty(s))
	{
		s->m_topIndex -= 1;
	}
	else
		cout << "空棧,彈出失敗" << endl;
}

int top(Stack s)
{
	if (!IsEmpty(s))
		return s->m_pArray[s->m_topIndex];
	else
		cout << "空棧,棧頂元素不存在" << endl;
}

void MakeEmpty(Stack s)
{
	s->m_topIndex = -1;
}

bool IsDisposeStack(Stack s)
{
	if (s->m_pArray != nullptr)
	{
		delete[] s->m_pArray;
		s->m_pArray = nullptr;
	}
	delete s;
	s = nullptr;
	if (s == nullptr)
		return true;
}

bool IsFull(Stack s)
{
	if (s->m_topIndex == s->m_capcity - 1)
		return true;
	return false;
}

bool IsEmpty(Stack s)
{
	if (s->m_topIndex == -1)
		return true;
	return false;
}

void Traverse(Stack s)
{
	cout << "從棧頂到棧低遍歷:";
	if (!IsEmpty(s))
	{
		int tmp = s->m_topIndex;
		while (tmp != -1)
		{
			cout << s->m_pArray[tmp] << " ";
			tmp--;
		}
		cout << endl;
	}
	else
		cout << "棧為空" << endl;
}