链式栈不带有头结点,top指针直接指向栈顶。
LinkStack.h
#include<iostream>
using namespace std;
template<class T>
struct LinkNode{
T data;
LinkNode<T> *link;
LinkNode(LinkNode<T>* pre = NULL){ link = pre; }
LinkNode(T& x, LinkNode<T> *pre = NULL){ data = x; link = pre; }
};
template<class T>
class LinkStack{
protected:
LinkNode<T> *top;
public:
LinkStack(){ top = NULL; }
~LinkStack(){ makeEmpty(); };
void makeEmpty();
bool isEmpty(){ return top == NULL ? true : false; }
bool push(T &x);
bool pop(T &x);
bool getTop(T &x);
int getSize();
void output();
};
template<class T>
void LinkStack<T>::makeEmpty(){
LinkNode<T> *p = top;
while (top != NULL){
p = top;
top = top->link;
delete p;
}
}
template<class T>
bool LinkStack<T>::push(T &x){
LinkNode<T> *p = new LinkNode<T>(x);
if(p == NULL){
cout << "内存分配错误!" << endl; exit(1);
}
p->link = top;
top = p;
return true;
}
template<class T>
bool LinkStack<T>::pop(T &x){
if (isEmpty() == true) return false;
LinkNode<T> *del = top;
x = del->data;
top = top->link;
delete del;
return true;
}
template<class T>
bool LinkStack<T>::getTop(T &x){
if (isEmpty() == true) return false;
x = top->data;
return true;
}
template<class T>
int LinkStack<T>::getSize(){
if (isEmpty() == true) return 0;
int cnt = 0;
LinkNode<T> *p = top;
while (p != NULL){
cnt++;
p = p->link;
}
return cnt;
}
template<class T>
void LinkStack<T>::output(){
cout << "top: ";
LinkNode<T> *p = top;
while (p != NULL){
cout << p->data << " ";
p = p->link;
}
cout << endl;
}
Test.cpp
#include"LinkStack.h"
#include<string>
using namespace std;
void main(){
LinkStack<string> intStack;
string str1 = "abcd", str2 = "efghji", str3 = "hello,world";
string str4, str5;
intStack.push(str1);
intStack.push(str2);
intStack.push(str3);
intStack.output();
cout << intStack.getSize() << endl;
intStack.getTop(str4);
cout << str4 << endl;
intStack.pop(str5);
intStack.output();
}