1️⃣5️⃣ 链式栈
#include <iostream>
using namespace std;
class ListStack{
private:
struct Node{
int data;
Node* next;
Node(int d, Node* n = 0):data(d), next(n) {}
};
Node* top;
public:
ListStack():top(0){}
~ListStack(){MakeEmpty();}
bool IsEmpty()const;
int Top()const;
void Push(const int i);
void Pop();
void MakeEmpty();
};
bool ListStack::IsEmpty()const{
return top==0;
}
int ListStack::Top()const{
if(IsEmpty())
throw"Stack is empty.";
return top->data;
}
void ListStack::Push(const int i){
top = new Node(i, top);
}
void ListStack::Pop(){
if(IsEmpty())
throw"Stack is empty. Cannot delete.";
Node* p = top;
top = top->next;
delete p;
}
void ListStack::MakeEmpty(){
while(!IsEmpty())
Pop();
}
int main() {
ListStack s1;
s1.Push(1);
s1.Push(2);
cout << s1.Top() << endl;
s1.Push(3);
s1.Push(4);
cout << s1.Top() << endl;
s1.Pop();
cout << s1.Top() << endl;
return 0;
}