栈的链式存储称为链栈,链栈的基本操作的实现,本质上是单链表基本操作的简化,其算法都非常简单,其时间复杂度均为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;
}
如果有什么错误之处或好的建议,请大家提出来,互相学习,谢谢.....