【数据结构与算法】栈的基本运算(出栈、入栈、销毁栈等)及源码(顺序栈和链式栈)
生活随笔
收集整理的這篇文章主要介紹了
【数据结构与算法】栈的基本运算(出栈、入栈、销毁栈等)及源码(顺序栈和链式栈)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、順序棧
.h文件
.cpp文件
#include "SequenceStack.h"//初始化空順序棧 int InitStack(SequenceStack &S) {S.top = -1;return 1; }//判順序棧空 int StackEmpty(SequenceStack &S) {if (S.top == -1)return 1;elsereturn 0; }//入棧 int Push(SequenceStack &S, DataType item) {if (S.top >= STACKSIZE - 1){cout << "棧滿" << endl;return 0;}S.top++;S.items[S.top] = item;return 1; }//出棧 int Pop(SequenceStack &S, DataType &item) {if (S.top <= -1){cout << "棧空" << endl;return 1;}item = S.items[S.top];S.top--;return 1; }//取棧頂 int GetTop(SequenceStack &S, DataType &item) {if (S.top <= -1){cout << "棧空" << endl;return 1;}item = S.items[S.top];return 1; }//遍歷棧 void printfStack(SequenceStack &S) {for (int i = 0; i < S.top; i++){cout << S.items[i] << " ";}cout << endl; }main.cpp測試文件
#include "SequenceStack.h" using namespace std;int main() {DataType result;SequenceStack myStack;InitStack(myStack);for (int i = 0; i < 10; i++)Push(myStack, i + 10);cout << "入棧后,棧里面的元素:" << endl;printfStack(myStack);while (StackEmpty(myStack) != 1)Pop(myStack, result);cout << "出棧后,棧里面的元素:" << endl;printfStack(myStack);system("pause");return 0; }測試結果:
二、鏈式棧
.h文件
.cpp文件
#include "LinkStack.h"//初始化空鏈表 int InitStack(LinkNode* &top) {top = new LinkNode;if (top == NULL){cout << "初始化錯誤!" << endl;return 0;}top->next = NULL;return 1; }//判鏈棧空 int StackEmpty(LinkNode *top) {if (top->next == NULL)return 1;elsereturn 0; }//入棧 int Push(LinkNode *top, DataType item) {LinkNode* t = new LinkNode; //生成新的節點if (t == NULL){cout << "內存不足" << endl;return 0;}t->data = item; t->next = top->next;top->next = t;return 1; }//出棧 int Pop(LinkNode *top, DataType &item) {if (top->next == NULL){cout << "棧空" << endl;return 0;}LinkNode* t = top->next;top->next = t->next;item = t->data;delete t;return 1; }//取棧頂元素 int GetTop(LinkNode *top, DataType &item) {if (top->next == NULL){cout << "棧空" << endl;return 1;}item = top->next->data;return 1; }//釋放鏈棧 void Destroy(LinkNode *&top) {LinkNode *p;while (top != NULL){p = top;top = top->next;delete p;} }//遍歷棧 void printfStack(LinkNode* top) {LinkNode* p = top->next;while (p){cout << p->data << " ";p = p->next;}cout << endl; }main.cpp測試文件
#include "LinkStack.h"int main() {int a;DataType result;LinkNode* myStack;InitStack(myStack);for (int i = 0; i <= 10; i++){Push(myStack, i + 10); //入棧GetTop(myStack, a); //獲取棧頂的元素cout << a << endl; //打印出元素}cout << "遍歷棧:" << endl;printfStack(myStack); //遍歷棧while (StackEmpty(myStack) != 1){Pop(myStack, result); //出棧}cout << "遍歷棧:" << endl;printfStack(myStack); //遍歷棧Destroy(myStack);system("pause");return 0; }測試結果:
關于棧的基本運算的介紹
總結
以上是生活随笔為你收集整理的【数据结构与算法】栈的基本运算(出栈、入栈、销毁栈等)及源码(顺序栈和链式栈)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue:Axios前端拦截器
- 下一篇: 多线程速成