C++类模板 实现栈的链式存储结构 《数据结构》(北京科海) (部分摘抄)

       栈的链式存储称为链栈,链栈的基本操作的实现,本质上是单链表基本操作的简化,其算法都非常简单,其时间复杂度均为O(1),下面是实现代码:

/*
Filename: LinkStack.h
Description: The chained storage structure of stack
Date: November 16, 2012
*/

#ifndef LINKSTACK_H
#define LINKSTACK_H

#include <iostream>
using namespace std;

template<class T> class LinkStack;

template<class T>
class Node
{
	friend class LinkStack<T>;

public:
	Node():next(NULL)
	{

	}

	Node(const T &item):data(item), next(NULL)
	{

	}

	~Node()
	{

	}

private:
	T data;
	Node<T> *next;
};


//栈的链式存储类定义
template<class T>
class LinkStack
{
public:
	LinkStack()
	{
		top = NULL;
	}

	~LinkStack()
	{
		Node<T> *p;
		while (top)
		{
			p = top->next;
			delete top;
			top = p;
		}
	}

public:
	void Push(T x);
	T Pop();
	T GetTop();
	bool Empty();
	void Print();

private:
	Node<T> *top;
};


//栈的链式存储 类实现
template<class T>
void LinkStack<T>::Push(T x)
{
	Node<T> *newNode = new Node<T>(x);
	newNode->next = top;
	top = newNode;
}


template<class T>
T LinkStack<T>::Pop()
{
	if (top == NULL)
	{
		throw "溢出";
	}

	T temp = top->data;
	Node<T> *tempNode = top;
	top = top->next;
	delete tempNode;

	return temp;
}


template<class T>
T LinkStack<T>::GetTop()
{
	if (top)
	{
		return top->data;
	}

	return NULL;
}


template<class T>
bool LinkStack<T>::Empty()
{
	if (top)
	{
		return false;
	}
	return true;
}


template<class T>
void LinkStack<T>::Print()
{
	if (!Empty())
	{
		Node<T> *tempNode = top;

		while (tempNode)
		{
			cout << tempNode->data << " ";
			tempNode = tempNode->next;
		}

		cout << endl;
	}

}

#endif




#include "LinkStack.h"

int main()
{
	LinkStack<int> Ls;
	Ls.Push(2);
	Ls.Push(4);
	Ls.Push(6);
	Ls.Print();
	cout << "---------------------" << endl;

	cout << "栈顶元素:" << Ls.GetTop() << endl;
	Ls.Pop();
	cout << "栈顶元素:" << Ls.GetTop() << endl;
	Ls.Print();

	system("pause");
	return 0;
}


    如果有什么错误之处或好的建议,请大家提出来,互相学习,谢谢.....

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值