1. 程式人生 > >陣列實現棧功能(C++練習記錄)

陣列實現棧功能(C++練習記錄)

Q:通過 陣列 實現 棧 功能

A:

MyStack.h

#ifndef MYSTACK_H
#define MYSTACK_H

/******************************/
/*棧實現 2017.03.02 by hyc*****/
/******************************/

class MyStack
{
public:
	MyStack(int size);    //初始化棧空間
	~MyStack();//回收棧空間記憶體
	void clearStack();//清空棧
	bool stackEmpty();//判空棧,若空返回true
	bool stackFull();//判滿棧,若滿返回true
	int stackLength();//棧中元素個數
	bool push(char elem);//元素入棧,棧頂上升
	bool pop(char &elem);//元素出棧,棧頂下降
	void stackTraverse(bool isFromBottom);//遍歷棧中元素 isFromBottom=1,從棧底遍歷
private:
	char *m_pBuffer;//棧空間指標
	int m_isize;//棧容量
	int m_itop;//棧頂,也是棧中元素個數
};

#endif // !MYSTACK_H


MyStack.cpp

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

MyStack::MyStack(int size)
{
	m_isize = size;
	m_pBuffer = new char[size];
	m_itop = 0;
}

MyStack::~MyStack()
{
	delete[] m_pBuffer;
}

void MyStack::clearStack()
{
	m_itop = 0;
}

bool MyStack::stackEmpty()
{
	return 0 == m_itop ? true : false;
}

bool MyStack::stackFull()
{
	return m_isize == m_itop ? true : false;
}

int MyStack::stackLength()
{
	return m_itop;
}

bool MyStack::push(char elem)
{
	if (stackFull())
	{
		return false;
	}
	m_pBuffer[m_itop] = elem;
	m_itop++;
	return true;
}

bool MyStack::pop(char &elem)
{
	if (stackEmpty())
	{
		return false;
	}
	m_itop--;
	elem = m_pBuffer[m_itop];
	return true;
}

void MyStack::stackTraverse(bool isFromBottom)
{
	if (isFromBottom)
	{
		for (int i = 0; i < m_itop; i++)
		{
			cout << m_pBuffer[i] << ",";
		}
	}
	else
	{
		for (int i = m_itop-1; i >= 0; i--)
		{
			cout << m_pBuffer[i] << ",";
		}
	}
}

demo.cpp:用於測試棧功能實現情況
#include "MyStack.h"
#include <iostream>
using namespace std;

/******************************/
/*棧實現 2017.03.02 by hyc*****/
/******************************/

int main(void)
{
	MyStack *pStack = new MyStack(5);
	
	pStack->push('h');//棧底
	pStack->push('e');
	pStack->push('l');
	pStack->push('l');
	pStack->push('o');//棧頂
	if (pStack->stackFull()){
		cout << "棧滿" << endl;
	}
	pStack->stackTraverse(true);
	cout << endl;

	char ch;
	pStack->pop(ch);
	cout << ch << endl;
	if (pStack->stackEmpty()){
		cout << "棧空" << endl;
	}
	if (pStack->stackFull()){
		cout << "棧滿" << endl;
	}
	pStack->stackTraverse(false);

	cout << pStack->stackLength() << endl;
	pStack->clearStack();
	if (pStack->stackEmpty()){
		cout << "棧空" << endl;
	}
	delete pStack;
	pStack = NULL;
	system("pause");
	return 0;
}

輸出結果:


注意:本次練習只實現了簡單的int型別的棧功能,可以使用模板類進一步實現其多型別支援。並且本程式有很多不完善的地方,如分配空間等的異常檢測。