About:Stack(利用链表实现)

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

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


template <typename T> 
class Stack : public List<T> 
{
	//将列表的首/末端作为栈顶/底
	public: //size()、empty()以及其它开放接口,均可直接沿用

		void push(T const& e) 
		{
			List<T>::insertAsLast(e);
		} //入栈:等效于将新元素作为列表的首元素插入
		
		T pop() 
		{ 
			return List<T>::remove(List<T>::last());
		} //出栈:等效于删除列表的首元素
		
		T& top() 
		{
			return List<T>::last()->data;
		} //取顶:直接返回列表的首元素
};


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;
}
发布了17 篇原创文章 · 获赞 17 · 访问量 163

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105461983
今日推荐