关于栈的链式存储结构,下面用的是单链表头插法创建栈,因为头插法的特点是在头结点(frist)与NULL空结点(first ->next)之间插入各结点,存储数据的入栈顺序和出栈顺序是相反的,和栈的特点很相似,工作指针如top指针一样,始终指向栈顶(第一个结点)。下代码如有不当之处,请指正!
#include<iostream>
//#include<stdlib.h>
using namespace std;
struct Stack {
int data;
struct Stack *next;
};
Stack *CreatStack() {
Stack *p;
p = new Stack; //p = (Stack *)malloc(sizeof(Stack));
p->data = NULL; //头结点不存放数据域
p->next = NULL; //栈底
return p;
}
Stack *PushStack(Stack *p) {
Stack *q;
cout << "进栈顺序:" << endl;
//下面用头插法构建链式栈,和单链表的头插法没有区别
for (int i = 0; i < 9; i++) {
q = new Stack;
q->data = i;
cout << q->data << "-->";
q->next = p->next;
p->next = q;
}
cout << "进栈结束" << endl;
return p;
}
void PrintStack(Stack *p) { //出栈
cout << "出栈顺序:" << endl;
p = p->next;
for (p->next; p != NULL; p = p->next) {
cout << p->data << "-->";
}
cout << "出栈结束" << endl;
}
void InsertStack(Stack *first,int x) { //在栈顶插入结点
Stack *p;
p = new Stack;
p->data = x;
p->next = first->next;
first->next = p;
}
void DestoryStack(Stack *first) { //销毁栈
do{
Stack *p;
p = first;
first = first->next;
delete p; //该步一定要在上面步骤之后
p = NULL; //避免出现迷途指针
} while (first != NULL);
cout << "链栈已销毁" << endl;
}
int main() {
Stack *p,*s;
p = CreatStack();
s = PushStack(p);
//InsertStack(s, 11);
DestoryStack(s);
//PrintStack(s);
}