链式栈

链式栈

//
//  链式栈
//
//  Created by chenshang on 14-2-6.
//  Copyright (c) 2014年 chenshang. All rights reserved.
//

#ifndef TestList_LinkStack_h
#define TestList_LinkStack_h

typedef int T;
//创建栈结点
class StackNode{
public:
    //初始化
    StackNode(T data ,StackNode* next=NULL):data(data),next(next){}
    T data;
    StackNode* next;
};


//创建链式栈
class LinkStack{
public:
    LinkStack():top(NULL){}
    ~LinkStack(){
        Empty();
    }
public:
    void Empty();//置空
    void push(const T item);//入栈
    T pop();//出栈
    T getTop()const;//获得栈顶元素
    void print();
    bool isEmpty()const{
        return top==NULL;
    }
private:
    StackNode* top;
};

void LinkStack::Empty(){
    StackNode* pmove;
    while (top!=NULL) {
        pmove=top;
        top=top->next;
        delete pmove;
    }
}
void LinkStack::push(T item){
    //创建一个结点 移动top指针
    top= new StackNode(item,top);
}
T LinkStack::getTop() const{
    if (isEmpty()) {
        cout<<"There is no elements!"<<endl;
        exit(1);
    }
    return top->data;
}
T LinkStack::pop(){
    if (isEmpty()) {
        cout<<"There is no elements!"<<endl;
        exit(1);
    }
    StackNode* pdel =top;
    top =top->next;
    T temp =pdel->data;
    delete pdel;
    return  temp;
}

void LinkStack::print(){
    StackNode* pmove = top;
    cout<<"top";
    while (pmove!=NULL) {
        cout<<"-->"<<pmove->data;
        pmove=pmove->next;
    }
    cout<<"-->bottom"<<endl<<endl<<endl;
}

#endif











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值