1.思路
节点结构体为:一个int数值,一个指向下一个节点的指针Struct* next。设定一个链表头节点p,每次入栈的节点都放在p点的下一个节点,前面的节点则依次往后推移一位;每次出栈时将p->next对应节点值输出,并将p->next指向p->next->next;当p->next为nullptr则表明栈为空;当p为nullptr,表明栈不存在。
2.代码
#include <iostream>
using namespace std;
struct Stack {
int value;
struct Stack *next;
};
Stack* CreateStack() {
Stack* p = (Stack*)malloc(sizeof(Stack));
p->value = 0;
p->next = nullptr;
return p;
}
bool isEmpty(Stack* p) {
if(p == nullptr) {
cout << "stack creats failed" << endl;
return true;
}
return p->next == nullptr;
}
Stack* PushStack(Stack* p, int value) {
if(p == nullptr) {
cout << "stack creats failed" << endl;
return nullptr;
}
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->value = value;
tmp->next = p->next;
p->next = tmp;
return p;
}
int PopStack(Stack* p) {
if(p == nullptr) {
cout << "stack creats failed" << endl;
return -100000000;
}
Stack* tmp = p->next;
p->next = tmp->next;
int res = tmp->value;
free(tmp);
return res;
}
void Destroy(Stack* p) {
while(!isEmpty(p)) {
PopStack(p);
}
free(p);
p = nullptr;
}
int main() {
Stack* p = CreateStack();
cout << "push 0-9" << endl;
for(int i = 0; i < 10; ++i) {
p = PushStack(p, i);
}
cout << "pop stack until it's empty" << endl;
while(!isEmpty(p)) {
cout << PopStack(p) << endl;
}
cout << "push 22" << endl;
p = PushStack(p, 22);
cout << "push 6" << endl;
p = PushStack(p, 6);
cout << "push 11" << endl;
p = PushStack(p, 11);
cout << "pop" << endl;
cout << PopStack(p) << endl;
cout << "pop" << endl;
cout << PopStack(p) << endl;
cout << "push 8" << endl;
p = PushStack(p, 8);
cout << "pop" << endl;
cout << PopStack(p) << endl;
cout << "pop" << endl;
cout << PopStack(p) << endl;
Destroy(p);
return 0;
}
3.运行结果