004.Stack(利用链表实现)

基于上一次业已实现的链表数据结构,这里贴出基于其实现的Stack数据结构,供大家学习参考交流。

#pragma once
#include"Vector.h"//以向量类,派生出模板类


template <typename T>
class Stack : public Vector<T>
{	//将向量的首/末端作为栈底/顶
public:
	//size()、empty()以及其它开放接口,均可直接沿用
	void push(T const& e)
	{
		//值得注意的是:由于insert接口业已在标准库中有其自己的实现,所以这里要显示的指明
		//所调用的是那一个重载版本
		Vector<T>::insert(e);
	} //入栈:等效于将新元素作为向量的末元素插入

	T pop()
	{
		return Vector<T>::remove(Vector<T>::size() - 1);
	} //出栈:等效于删除向量的末元素

	T& top()
	{
		return (*this)[Vector<T>::size() - 1];
	} //取顶:直接返回向量的末元素
};


int main()
{
	int i;
	Stack<int>stk;
	for (i = 0; i < 10; i++)
	{
		//进行100次入栈操作
		stk.push(i);
	}
	cout << "-------------------01.取顶操作--------------------------------------------" << endl;
	int top = stk.top();
	cout << "the current top element of this stack is:" << top << endl;
	cout << endl;

	cout << "-------------------02.不断地弹栈,直到栈为空,并输出栈中的内容-------------" << endl;
	while (!stk.empty())
	{
		cout << stk.top() << " ";
		stk.pop();
	}
	cout << endl;
	cout << endl << "test over!" << endl;

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值