链式栈
//
// 链式栈
//
// 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