顺序栈写的还是比较多的,由于书上没有链式栈的实现,所以在这里我先实现一下,留个记录。
头文件
#ifndef LINKLISTSTACK_H
#define LINKLISTSTACK_H
//设置指针指向前继元素
struct Node{
int data;
Node *pre;
};
class LStack{
private:
Node *top;
public:
LStack();
~LStack();
bool isEmpty()const;
void push(const int &elem);
bool pop(int &elem);
bool getTop(int &elem)const;
};
<pre name="code" class="cpp">#include"linkListStack.h"
#include<iostream>
using std::cout;
using std::endl;
LStack::LStack(){
top = NULL;
}
LStack::~LStack(){
Node *pre = top->pre, *p=top;
while (pre != NULL){
delete p;
p = pre;
pre = pre->pre;
}
delete p;
}
bool LStack::isEmpty()const{
return top == NULL;
}
void LStack::push(const int &elem){
Node *s = new Node;
s->data = elem;
s->pre = top;
top = s;
}
bool LStack::pop(int &elem){
if (top == NULL) return false;
elem = top->data;
top = top->pre;
return true;
}
bool LStack::getTop(int &elem)const{
if (top == NULL) return false;
elem = top->data;
return true;
}
main函数
#include<iostream>
#include"linkListStack.h"
using namespace std;
int main(){
LStack sta;
sta.push(1);
sta.push(2);
sta.push(3);
sta.push(4);
sta.push(5);
while (!sta.isEmpty()){
int num;
if (sta.pop(num)) cout << num << endl;
else cout << "!!!!" << endl;
}
system("pause");
return 0;
}