栈-链栈
原创
©著作权归作者所有:来自51CTO博客作者xiangjie256的原创作品,请联系作者获取转载授权,否则将追究法律责任
LinkedStack.h
#ifndef LINKEDSTACK_H
#define LINKEDSTACK_H
#include<iostream>
#include"../T2/LinkedList.h" //LinkNode
#include"Stack.h"
using namespace std;
template<typename T>
class LinkedStack:public Stack<T>{
public:
LinkedStack():top(NULL){}
~LinkedStack(){makeEmpty();}
void Push(const T &x);
bool Pop(T &x);
bool getTop(T &x) const;
bool IsEmpty() const{
return top==NULL?true:false;
}
bool IsFull() const{
return false;
}
int getSize() const;
void makeEmpty();
friend ostream& operator<<(ostream& os,LinkedStack<T>& s){
LinkNode<T> *p = s.top;
while(NULL!=p){
cout << p->data << " ";
p = p->link;
}
cout << endl;
return os;
}
private:
LinkNode<T> *top;
};
#endif // LINKEDSTACK_H
#include"LinkedStack.h"
#include<assert.h>
template<typename T>
void LinkedStack<T>::makeEmpty()
{
LinkNode<T> *p;
while(NULL!=top){
p = top;
top = top->link;
delete p;
}
}
template<typename T>
void LinkedStack<T>::Push(const T &x)
{
top = new LinkNode<T>(x,top);
assert(NULL!=top);
}
template<typename T>
bool LinkedStack<T>::Pop(T &x)
{
if(IsEmpty()){
return false;
}else{
x = top->data;
LinkNode<T>* p;
p = top;
top = top->link;
delete p;
return true;
}
}
template<typename T>
bool LinkedStack<T>::getTop(T &x) const
{
if(IsEmpty()){
return false;
}else{
x = top->data;
return true;
}
}
template<typename T>
int LinkedStack<T>::getSize() const
{
if(IsEmpty()){
return 0;
}else{
int size = 0;
LinkNode<T> *p = top;
while(NULL!=p){
p = p->link;
size++;
}
return size;
}
}
int main()
{
LinkedStack<int> ls;
for(int i=0;i<10;++i){
ls.Push(i);
}
cout << ls;
cout << ls.getSize() << endl;
int num;
for(int i=0;i<5;++i){
ls.Pop(num);
}
cout << ls;
}
9 8 7 6 5 4 3 2 1 0
10
4 3 2 1 0