数据结构:顺序栈的基本操作及实现
生活随笔
收集整理的這篇文章主要介紹了
数据结构:顺序栈的基本操作及实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、棧的結(jié)構(gòu)定義
#define MaxSize 100 #define DataType inttypedef struct {DataType data[MaxSize];int top; }SeqStack, *PSeqStact;二、基本操作的實現(xiàn)
//初始化棧 PSeqStact Init_Stack() {PSeqStact S;S = (PSeqStact)malloc(sizeof(SeqStack));if (S) {S->top = -1;printf("初始化成功\n");}return S; }//判斷棧空 int Empty_Stack(PSeqStact S) {if (S->top == -1) {return 1; //棧空}return 0; //棧不空 }//入棧 int Push_Stack(PSeqStact S, DataType x) {if (!S || S->top == MaxSize - 1) {return 0; //失敗}S->data[++S->top] = x;return 1; //成功 }//出棧,出棧元素由x帶回 int Pop_Stack(PSeqStact S, DataType* x) {if (S->top == -1) {return 0; //失敗}*x = S->data[S->top--];return 1; //成功 }//取棧頂元素 int GetTop_Stack(PSeqStact S, DataType* x) {if (Empty_Stack(S)) {return 0; //棧空}*x = S->data[S->top];return 1; }//銷毀棧 void Destroy_Stack(PSeqStact* S) {free(*S);*S = NULL;printf("銷毀成功\n");return; }//顯示棧中元素 void Show_Stack(PSeqStact S) {printf("棧中元素有:\n");for (int i = 0;i <= S->top; i++) {printf("%d ", S->data[i]);}printf("\n"); }三、測試代碼
int main() {int x = 0;PSeqStact S;S = Init_Stack();for (int i = 0; i < 5; i++) {if (Push_Stack(S, i))printf("入棧成功,元素為:%d\n", i);}Show_Stack(S);if (Pop_Stack(S, &x)) {printf("出戰(zhàn)成功,出棧元素為:%d\n", x);}Show_Stack(S);if (GetTop_Stack(S, &x)) {printf("棧頂元素為:%d\n", x);}Destroy_Stack(&S);return 0; }四、測試結(jié)果
?
總結(jié)
以上是生活随笔為你收集整理的数据结构:顺序栈的基本操作及实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu更新过程被中断后的问题
- 下一篇: mysqld命令相关介绍