顺序栈和链式栈

相信大家对栈都不陌生,栈作为一种基础的数据结构,在很多地方都会用到,在这里整理一下顺序栈和链式栈的一些基础操作。

1.顺序栈

#pragma onc
# define MAX_SIZE 10
class SeqStack
{
public:
	SeqStack():top(-1),size(MAX_SIZE)
	{
		arr = new int[size];
	}
	~SeqStack()
	{
		delete[] arr;
	}
	//判断栈满
	bool Full()
	{
		return top == size - 1;
	}
	//判断栈空
	bool Empty()
	{
		return top == -1;
	}
	//入栈
	void Push(int value)
	{
		if (!Full())
		{
			arr[++top] = value;
		}
	}
	//出战
	int Pop()
	{
		if (!Empty())
		{
			return arr[top--];
		}
	}
	//得到栈顶元素
	int GetTopEle()
	{
		if (!Empty())
		{
			return arr[top];
		}
	}

private:
	int top;
	int size;
	int* arr;
};

2.链式栈

#pragma once
# define VALUE_TYPE int
typedef struct Node
{
	VALUE_TYPE data;
	Node* next;
};
class LinkStack
{
public:
	LinkStack():top(nullptr),length(0)
	{
	}
	~LinkStack()
	{
		if (top != nullptr)
		{
			while (!Empty())
			{

			}
		}
	}
	//判断栈是否为空
	bool Empty()
	{
		return length == 0;
	}
	//入栈操作
	bool Push(VALUE_TYPE value)
	{
		Node* newNode = new Node;
		newNode->data = value;
		if (!Empty())
		{
			newNode->next = top;
			top = newNode;
		}
		else
		{
			top = newNode;
			top->next = nullptr;
		}
		++length;
		return true;
	}
	//出栈操作
	VALUE_TYPE Pop()
	{
		if (!Empty())
		{
			Node *node = top;
			top = top->next;
			int data = node->data;
			delete node;
			--length;
			return data;
		}
	}
	//获取栈顶元素
	VALUE_TYPE GetTopEle()
	{
		if (!Empty())
		{
			return top->data;
		}
	}
private:
	Node* top;
	int length;
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值