链式栈的使用
本篇博客遇上篇博客不同,不需要加条件判断栈是否为满,为了提高效率我们可以使用链表的前插法来表示栈,整体使用方法和单链表类似
/*数据结构与算法之 栈的链式存储 实验目的: (1) 实现栈的存储结构设计; (2) 实现栈的操作算法设计; (3) 利用栈实现应用问题的解决; 实验内容: 栈的初始化 打印栈内所有元素 判断栈空 入栈和出栈算法设计; */ #include<iostream> #include<Windows.h> using namespace std; static int length = 0; typedef struct _LqStack { int data; struct _LqStack *next; //指向下一节点的指针 }LqStack,LqNode; //初始化链式栈 bool InitLq(LqStack* &Lq) { Lq = new LqStack; if (!Lq) return false; Lq->data = -1; Lq->next = NULL; return true; } //前插法入队 bool push(LqStack* &Lq, LqNode *s) { if (!Lq) return false; s->next = Lq->next; Lq->next = s; length++; return true; } //打印链表 void PrintLq(LqStack* &Lq) { if (!Lq) return ; LqStack *p = Lq->next; cout << "链式栈的元素依次是: "; while (p) { cout << p->data << " "; p = p->next; } return; } //出栈 bool PopLq(LqStack* &Lq, int &Element) { if (!Lq) return false; LqStack *p = Lq; if (Lq->next == NULL) { cout << "这是个空栈! " << endl; return false; } Lq = Lq->next; Element = Lq->data; delete p; p = Lq; length--; return true; } int main(void) { LqStack *Lq; LqNode *s; if (InitLq(Lq)) { cout << "初始化链式栈成功! " << endl; } else { cout << "初始化链式栈失败! " << endl; } int num; //入栈的个数 int Element; //记录出栈元素的值 cout << "请输入你想要入栈的个数: "; cin >> num; //入栈,使用链式存储 for (int i = 0; i < num; i++) { s = new LqNode; cout << "请输入你想要插入的元素: "; cin >> s->data; if (push(Lq, s)) { cout << "链式栈插入元素成功! 插入的元素是: "<<s->data << endl; } else { cout << "链式栈插入元素失败! " << endl; } } //打印链式栈 PrintLq(Lq); cout << "现在栈的个数是: " << length << endl; //出栈 cout << "请输入你想要出栈的个数: "; cin >> num; for (int i = 0; i < num; i++) { if (PopLq(Lq, Element)) { cout << "出栈成功! 出栈的元素是: " << Element << endl; } else { cout << "出栈失败! " << endl; } } PrintLq(Lq); cout << "现在栈的个数是: " << length << endl; //栈的初始化 打印栈内所有元素 判断栈空 入栈和出栈算法设计; system("pause"); return 0; }