数据结构-栈的一些基础操作c++代码

堆栈(简称栈) 是一种操作受限的线性表,只允许在表的同一端进行插入和删除操作,且这些操作是按先进后出的原则进行的。
template <class T>
struct SLNode
{
	T data;                     //数据域
	SLNode<T> *next;            //指针域

	SLNode(SLNode *nextNode = NULL)                      //构造函数
	{
		next = nextNode;
	}
	
	SLNode(const T &item, SLNode *nextNode = NULL)      //构造函数
	{
		data = item;
		next = nextNode;
	}
};

//顺序栈
template <class T>
class AStack
{
	public:
		AStack(int MaxStackSize)                              //构造函数
		{
			size = MaxStackSize;
			stackArray = new T[MaxStackSize];
			top = -1;
		}

		~AStack()                              //析构函数
		{
			delete []stackArray;
		}

		bool Push(const T &item)              //向栈顶压入一个元素
		{
			if (IsFull())
			{
				cout << "Pushing into a full stack!" << endl;
				return false;
			}
			stackArray[++top] = item;
			return true;
		}

		bool Pop(T &item)                     //从栈顶弹出一个元素
		{
			if (IsEmpty())
			{
				cout << "Poping from an empty stack!" << endl;
				return false;
			}
			item = stackArray[top--];
			return true;
		}

		bool Peek(T &item) const              //存取栈顶元素
		{
			if (IsEmpty())
			{
				cout << "Peeking from an empty stack!" << endl;
				return false;
			}
			item = stackArray[top];
			return true;
		}

		int IsEmpty() const                    //检测栈是否为空
		{
			return top == -1;
		}

		int IsFull() const                     //检测是否满栈
		{
			return top == size-1;
		}

		void clear()                           //清空栈
		{
			top = -1;
		}

	private:
		int size;                              //数组的规模
		T *stackArray;                         //存放堆栈元素的数组
		int top;                               //栈顶所在数组元素的下标
};

//链式栈类LStack的定义和实现
template <class T>
class LStack
{
	public:
		LStack()                             //构造函数
		{
			top = NULL;
		}

		~LStack()                           //析构函数
		{
			clear();
		}
		
		void clear()                       //清空栈
		{
			SLNode<T> *temp;
			while(!IsEmpty())
			{
				temp = top->next;
				delete top;
				top = temp;
			}
		}

		bool Push(const T &item)          //向栈顶压入一个元素
		{
			top = new SLNode<T>(item, top);
			return true;
		}

		bool Pop(T &item)                 //从栈顶弹出一个元素
		{
			if(IsEmpty())
			{
				cout << "Poping from an empty stack!" << endl;
				return false;
			}
			item = top->data;
			SLNode<T> *temp = top;
			top = top->next;

		}

		bool Peek(T &item) const         //读取栈顶元素
		{
			if(IsEmpty())
			{
				cout << "Poping from an empty stack!" << endl;
				return false;
			}
			item = top->data;
			return true;
		}

		int IsEmpty() const
		{
			return top == NULL;
		}
	private:
		SLNode<T> *top;
		
};


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值