c語言:順序棧的實現
阿新 • • 發佈:2019-01-09
#include<iostream> #include<stdio.h> #include<math.h> #define STACK_INIT_SIZE 100 #define STACK_INCREMENT 10 using namespace std; typedef struct Stack //結構體定義 { int *elem; //資料域 int top; //順序棧棧頂 int stacksize; //順序棧當前長度 }Stack; //函式宣告部分 void Error(char *s); //錯誤處理函式 Stack Creat_Stack();//若干個元素的順序棧 void Destroy_Stack(Stack & l); //銷燬順序棧 void Clear_Stack(Stack & l); //清空順序棧 int Getlength_Stack(Stack &l); //計算順序棧長度 void Gettop_Stack(Stack &l, int e); //得到順序棧棧頂元素 void Push_Stack(Stack &L, int e); //壓棧操作函式 void Pop_Stack(Stack &L, int e); //出棧操作函式 void Increment_Stack(Stack & l); //增加順序棧空間函式 void Print_Stack(Stack & l); //輸出順序棧元素函式 //函式實現部分 void Error(char *s) { cout << s << endl; exit(1); } Stack Creat_Stack() { int length = 0; int data = 0; Stack l; l.elem = new int[STACK_INIT_SIZE]; if (!l.elem) Error("記憶體申請失敗!"); l.top = -1; l.stacksize = STACK_INIT_SIZE; cout << "請輸入順序棧長度:"; cin >> length; cout << "請輸入順序棧元素內容:" << endl; for (int i = 0; i < length; i++) { cin >> data; l.elem[i] = data; //這一步是重點 l.top++; } cout << "順序棧建立成功!" << endl; return l; } void Destroy_Stack(Stack &l) { delete[] l.elem; l.top = -1; l.stacksize = 0; cout << "該順序棧銷燬成功!" << endl; } void Clear_Stack(Stack &l) { l.top = -1; } int Getlength_Stack(Stack & l) { return (l.top + 1); } void Gettop_Stack(Stack &l, int e) { if (l.top == -1) Error("該棧為空棧!"); e = l.elem[l.top]; cout << "該順序棧的棧頂元素是:"; cout << e << endl; } void Increment_Stack(Stack &l) { int *newstack = new int[l.stacksize + STACK_INCREMENT]; if (!newstack) Error("儲存分配失敗!"); for (int i = 0; i < l.top; i++) { newstack[i] = l.elem[i]; } l.elem = newstack; delete[] l.elem; l.stacksize += STACK_INCREMENT; } void Push_Stack(Stack &l, int e) { if (l.top == (l.stacksize - 1)) Increment_Stack(l); l.elem[++l.top] = e; } void Pop_Stack(Stack &l, int e) { if (l.top == -1) Error("該順序棧為空棧!"); e = l.elem[l.top--]; cout << e << endl; } void Print_Stack(Stack &l) { cout << "該順序棧的元素是:" << endl; for (int i = l.top; i > -1; i--) { cout << l.elem[i] << " "; } cout << endl; } int main() { Stack s; int d = 0; int t = 0; int q = 0; s = Creat_Stack(); cout << "該順序棧的長度是:" << Getlength_Stack(s) << endl; Print_Stack(s); Gettop_Stack(s, d); cout << "請輸入要入棧的元素:"; cin >> t; Push_Stack(s, t); cout << "該順序棧的長度是:" << Getlength_Stack(s) << endl; Print_Stack(s); cout << "出棧的元素是:"; Pop_Stack(s, q); Destroy_Stack(s); return 0; }