数据结构与算法——链栈

来源:互联网 发布:浙江政务服务软件 编辑:程序博客网 时间:2024/06/05 09:10

今天总结链栈。

什么是链栈?

链栈就是栈的链式存储结构,就跟单链表差不多。只不过头指针变成了栈顶指针,这个指针总是指向栈顶元素。栈底结点的指针域指向NULL,当top==NULL时,则栈为空.具体实现时,对比着单链表,然后结合图示,很容易就写出来了。

图示:

实现:

<span style="font-family:Courier New;font-size:14px;">#include <iostream>using namespace std;template <class T>struct Node {    T data;    struct Node<T> *next;};template <class T>class LinkStack{public:    LinkStack() {        top = NULL;  //空栈    }    ~LinkStack();   //析构函数 释放结点空间    void Push(T x);  //入栈    T Pop();         //出栈    T GetTop();     //得到栈顶元素    void PrintStack();  //打印栈内元素    bool IsEmpty();   //判断是否为空栈private:    struct Node<T> *top;};template <class T>void LinkStack<T>::Push(T x) {    Node<T> *p = new Node<T>;    p->data = x;    p->next = top;    top = p ;}template <class T>void LinkStack<T>::PrintStack() {    Node<T> * p = top;  //保存栈顶指针    while(top) {        cout<<top->data<<" ";        top = top->next;    }    top = p;  //使栈顶指针重新指向栈顶元素    cout<<endl;}template <class T>T LinkStack<T>::Pop() {    if(IsEmpty()) cout<<"栈为空";    Node<T> *p = top;    T x = top->data;    top = top->next;    delete p;    return x;}template <class T>bool LinkStack<T>::IsEmpty() {    if(top==NULL)        return true;    else        return false;}template <class T>T LinkStack<T>::GetTop() {    if(IsEmpty()) cout<<"栈为空"<<endl;    return top->data;}template <class T>LinkStack<T>::~LinkStack() {    while(top) {        Node<T> *p = top;        top = top->next;        delete p;    }}int main(){    LinkStack<int> stack;    for(int i=0;i<5;i++) {        stack.Push(i);    }    stack.PrintStack();    cout<<"出栈:"<<endl;    cout<<stack.Pop()<<endl;    stack.PrintStack();    cout<<"获取栈顶元素"<<endl;    cout<<stack.GetTop()<<endl;    return 0;}</span>


0 0
原创粉丝点击