链栈实现

实现链式栈,这里用的是不带头节点的单链表,链表的表头表示栈顶,入栈与出栈都在表头进行链式栈的类模版中只有一个数据成员,即top,它为栈顶指针,指向栈顶元素,初始值为NULL,表示空栈


#ifndef GUARD_NODE_h
#define GUARD_NODE_h
#define NULL 0
template<class T>
struct Node{
    T data;
    Node<T>* next;
    Node();
    Node(T e,Node<T>* p=NULL);
};
template<class T>
Node<T>::Node(){
    next=NULL;
}

template<class T>
Node<T>::Node(T e,Node<T>* p){
    next=p;
    data=e;
}
#endif


#ifndef GUARD_LINKLIST_h
#define GUARD_LINKLIST_h
#include"Node.h"
#include<iostream>
using namespace std;
#define NULL 0
template<class T>
class LinkStack{
private:
    Node<T>* top;
public:
    LinkStack();
    virtual~LinkStack();
    void Clear();//清空栈
    bool Push(const T& e);//入栈
    bool Pop(T& e);
    bool Top(T& e)const;//取栈顶元素
    int GetLength()const;//得到队列的长度
    bool IsEmpty()const;
    void print();
    LinkStack(const LinkStack<T>& e);//复制构造函数
    LinkStack<T>& operator=(const LinkStack<T>& e);//赋值符重载

};

template<class T>
LinkStack<T>::LinkStack(){
    top=NULL;
}

template<class T>
LinkStack<T>::~LinkStack (){
    Clear();
}

template<class T>
int LinkStack<T>::GetLength()const{
    Node<T>* p;
    int count=0;
    for(p=top;p!=NULL;p=p->next){
        ++count;
    }
    return count;
}

template<class T>
void LinkStack<T>::Clear(){
    Node<T>* p;
    while(top!=NULL){
        p=top;
        top=top->next ;
        delete p;
    }
}

template<class T>
void LinkStack<T>::print(){
    Node<T>* p=top;
    while(p){
        cout<<p->data<<" ";
        p=p->next;
    }
}

template<class T>
bool LinkStack<T>::Push(const T& e){
    Node<T>* p=new Node<T>(e,top);
    if(IsEmpty()){
        top=p;
        return true;
    }
    else{
        top=p;
        return true;
    }
}

template<class T>
bool LinkStack<T>::Pop(T& e){
    if(IsEmpty()){
        return false;
    }
    else{
        Node<T>*p=top;
        e=top->data;
        top=top->next;
        delete p;
        return true;
    }
}

template<class T>
bool LinkStack<T>::Top(T& e)const{
    if(top==NULL)
        return false;
    else{
        e=top->data;
        return true;
    }
}

template<class T>
bool LinkStack<T>::IsEmpty()const{
    if(top==NULL)
        return true;
    else
        return false;
}

#endif


#include"LinkStack.h"
#include<iostream>
#include<vector>
using namespace std;

int main(){
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    LinkStack<int> ls;
    int i=0,j=0;
    while(i!=10){
        ls.Push(a[i]);
        ++i;
    }
        ls.print();
        cout<<endl;
        cout<<ls.GetLength()<<endl;
        int e;
        ls.Pop(e);
        cout<<e<<endl;
        ls.Clear();
        cout<<ls.GetLength()<<endl;

    return 0;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值