您的位置:首页 > 理论基础 > 数据结构算法

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

2012-11-16 11:03 661 查看
       栈的链式存储称为链栈,链栈的基本操作的实现,本质上是单链表基本操作的简化,其算法都非常简单,其时间复杂度均为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;
}


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

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: