簡單易懂的順序棧實現
#include"stdafx.h" #include<iostream>
using namespace std; constexpr auto M = 5;//最多存放 int Stack[M];//順序棧 int top;//棧頂 void InitiaStack(int &top) {//初始化 top =-1; cout<<"初始化了一個空順序棧"<<endl; } int Empty(int top) {//檢查棧是否為空 return top == -1; } int Full(int top) {//檢查棧滿 return top == M - 1; } int GetTop(int Stack[],int &top) {//獲取棧頂 int item; if (Empty(top)) { cout << "空棧" << endl; return 0; } else { item = Stack[top]; cout << "當前棧頂元素為" << item<<endl; return 1; } } int Push(int Stack[], int &top, int item) { if (Full(top)) { cout << "當前棧空間不足,請結束進棧操作" << endl; return 0; } else { Stack[++top] = item;//進棧,修改棧頂 cout << "當前進棧元素為:" << item << endl; return 1; } } int Pop(int Stack[], int &top) { int item; if (Empty(top)) { return 0; } else { item = Stack[top--];//出棧,修改棧頂 cout << item << "出棧成功" << endl; return 1; } }
int main() {
InitiaStack(top); int item; cout << "請輸入進棧元素,以0結束" << endl; while (true) { cin >> item; if (item) { Push(Stack, top, item); } else { break; } } Pop(Stack, top); GetTop(Stack, top); return 0; }