顺序栈&链栈 C++实现

顺序栈

#include <iostream>
using namespace std;
const int StackSize=100;
template<class T>
struct Node {
    T data;
    Node* next;
};
template<class T>
class SeqStack
{
    public:
        SeqStack(){top=-1;}
        ~SeqStack(){}
        void Push(T x);
        T Pop();
        T GetTop(){if(top!=-1) return data[top];}
        int Empty(){if(top==-1)return 1;else return 0;}
    private:
        T data[StackSize];
        int top;
};
template<class T>
void SeqStack<T>::Push(T x)
{
    if(top==StackSize-1){throw "上溢";}
    data[++top]=x;
}
template<class T>
T SeqStack<T>::Pop()
{
    T x;
    if(top==-1){throw "下溢";}
    x=data[top--];
    return x;
}
int main()
{
    int x;
    SeqStack<int> s;
    s.Push(6);
    s.Push(7);
    s.Push(8);
    s.Push(9);
    s.Push(10);
    cout<<"当前栈顶元素为:"<<s.GetTop()<<endl;

    try
    {
        cout<<"请输入要入栈的元素"<<endl;
        cin>>x;
        s.Push(x);
    }catch(const char *str){cout<<str<<endl;}
    try
    {
        x=s.Pop();
        cout<<"执行一次出栈操作,删除元素: "<<x<<endl;
    }catch(const char *str){cout<<str<<endl;}
    if(s.Empty())
    {
        cout<<"栈为空"<<endl;
    }
    else
    {
        cout<<"栈非空"<<endl;
    }
    return 0;
}

运行结果

链栈

#include <iostream>
using namespace std;
template<class T>
struct Node {
    T data;
    Node* next;
};
template<class T>
class LinkStack
{
    public:
        LinkStack(){top=NULL;}
        ~LinkStack(){}
        void Push(T x);
        T Pop();
        T GetTop(){if(top!=NULL)return top->data;}
        bool Empty();
    private:
        Node<T> *top;
};
template<class T>
void LinkStack<T>::Push(T x)
{
    Node<T> *pre;
    pre=new Node<T>;
    pre->data=x;
    pre->next=top;
    top=pre;
}
template<class T>
T LinkStack<T>::Pop()
{
    Node<T> *pre=NULL;
    T x;
    if(top==NULL){throw "下溢";}
    x=top->data;
    pre=top;
    top=top->next;
    delete pre;
    return x;
}
template<class T>
bool LinkStack<T>::Empty()
{
    if(top==NULL)
    {
        return true;
    }
    else
    {
        return false;
    }
}
int main()
{
    int x;
    LinkStack<int> ls;
    ls.Push(6);
    ls.Push(7);
    ls.Push(8);
    ls.Push(9);
    ls.Push(10);
    cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;

    try
    {
        cout<<"请输入要入栈的元素"<<endl;
        cin>>x;
        ls.Push(x);
    }catch(const char *str){cout<<str<<endl;}
    cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;
    try
    {
        x=ls.Pop();
        cout<<"执行一次出栈操作,删除元素: "<<x<<endl;
    }catch(const char *str){cout<<str<<endl;}
    cout<<"当前栈顶元素为:"<<ls.GetTop()<<endl;
    if(ls.Empty())
    {
        cout<<"栈为空"<<endl;
    }
    else
    {
        cout<<"栈非空"<<endl;
    }
    return 0;

}


运行结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值