学无先后,达者为师

网站首页 编程语言 正文

数据结构之数组栈的实现

作者:assassin$ 更新时间: 2022-08-15 编程语言
关于栈
  • 栈的有关理论在我另外一文中写出,这篇文章只展示代码实现;
  • 数组栈非常容易实现,就不做其他叙述;
    注:数据结构系列将持续更新,欢迎交流讨论…
示例代码
  • 示例代码中提供两个构造函数实现数组栈;
  • 栈的清空仍然采用逻辑置空;
  • 栈的实现主要注意栈顶元素就可以了……
#include <iostream>

using namespace std;

#define MAXSIZE 13

class Stack
{
public:
	Stack();
	Stack(int Size);
	bool push(int data);
	bool pop();
	int getTop();
	int IsEmpty();//判断是否为空
	void Empty();//置空

private:
	int* m_pSt;
	int m_top;
	int m_curSize;
	int m_Capacity;
};

int main()
{
	Stack* pSt = new Stack;
	pSt->push(1);
	pSt->push(2);
	pSt->push(3);

	while (!pSt->IsEmpty())
	{
		cout << pSt->getTop() << " ";
		pSt->pop();
	}

	return 0;
}

Stack::Stack()
{
	this->m_pSt = new int[MAXSIZE];
	m_top = -1;
	m_curSize = 0;
	m_Capacity = MAXSIZE;
}

Stack::Stack(int Size)
{
	this->m_pSt = new int[Size];
	m_top = -1;
	m_curSize = 0;
	m_Capacity = Size;
}

bool Stack::push(int data)
{
	if (this->m_curSize >= this->m_Capacity || this->m_Capacity <= 0)
		return false;

	m_pSt[++m_top] = data;
	m_curSize++;

	return true;
}

bool Stack::pop()
{
	if (m_curSize <= 0)
		return false;

	m_curSize--;
	m_top--;

	return true;
}

int Stack::getTop()
{
	return this->m_pSt[m_top];
}

int Stack::IsEmpty()
{
	return m_top == -1;
}

void Stack::Empty()
{
	m_top = -1;
}

原文链接:https://blog.csdn.net/qq_46282869/article/details/126336641

栏目分类
最近更新