实现栈的基本操作(c语言)
生活随笔
收集整理的這篇文章主要介紹了
实现栈的基本操作(c语言)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
順序棧的介紹
一、實(shí)現(xiàn)順序棧的基本操作
二、各操作的代碼詳解
1.定義順序棧
2.構(gòu)建順序棧
3.順序棧的判空
4.順序棧的入棧
5.順序棧的出棧
6.讀取順序棧的棧頂元素
總代碼
順序棧的介紹
順序棧是指利用順序存儲(chǔ)結(jié)構(gòu)實(shí)現(xiàn)的棧,即利用一組地址連續(xù)的存儲(chǔ)單元依次存放自棧低到棧頂?shù)臄?shù)據(jù)元素,同時(shí)設(shè)置指針top指向棧頂元素在順序站的位置,本篇介紹順序棧的做法是將top指針先指向-1表示空棧,當(dāng)需要進(jìn)棧的時(shí)候top指針往后移動(dòng)再放入數(shù)據(jù),達(dá)到指針每次都是指向棧頂元素的效果。
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、實(shí)現(xiàn)順序棧的基本操作
二、各操作的代碼詳解
1.定義順序棧
代碼如下(示例):
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define MAX 100 typedef struct SeqStack{ int * data; int top; //棧頂指針 }SeqStack;2.構(gòu)建順序棧
代碼如下(示例):
void Initstack(SeqStack * L){ L->top=-1; L->data=(int *)malloc(sizeof(int)*MAX); }3.順序棧的判空
代碼如下(示例):
bool EmptyStack(SeqStack * L){ if(L->top==-1){printf("當(dāng)前棧空,請加入元素\n");return false;} elsereturn true; }4.順序棧的入棧
代碼如下(示例):
void Push(SeqStack * L ,int pushData){ if(L->top==MAX-1)return; L->top++; L->data[L->top]=pushData; printf("元素進(jìn)棧成功\n"); }5.順序棧的出棧
代碼如下(示例):
int Pop(SeqStack * L){ int popData; if(EmptyStack(L)==false)return; else{popData=L->data[L->top];printf("當(dāng)前出棧元素為:%d\n",popData);L->top--;return popData; }}6.讀取順序棧的棧頂元素
代碼如下(示例):
int GetTop(SeqStack * L){ int topData; if(EmptyStack(L)==false)return; else{topData=L->data[L->top];printf("當(dāng)前棧頂元素為:%d \n",topData);return topData; } }總代碼
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define MAX 100 typedef struct SeqStack{ int * data; int top; //棧頂指針 }SeqStack;void Menu(){ printf("\n"); printf("\t\t\t\t\t\t --順序棧的實(shí)現(xiàn)--\n"); printf("\t\t\t\t\t\t 1.元素進(jìn)棧\n"); printf("\t\t\t\t\t\t 2.元素出棧\n"); printf("\t\t\t\t\t\t 3.創(chuàng)建順序棧表\n"); printf("\t\t\t\t\t\t 4.查找棧頂元素\n"); printf("\t\t\t\t\t\t 0.退出\n");}bool EmptyStack(SeqStack * L){ if(L->top==-1){printf("當(dāng)前棧空,請加入元素\n");return false;} elsereturn true; }void Initstack(SeqStack * L){ L->top=-1; L->data=(int *)malloc(sizeof(int)*MAX); }void Push(SeqStack * L ,int pushData){ if(L->top==MAX-1)return; L->top++; L->data[L->top]=pushData; printf("元素進(jìn)棧成功\n"); }int Pop(SeqStack * L){ int popData; if(EmptyStack(L)==false)return; else{popData=L->data[L->top];printf("當(dāng)前出棧元素為:%d\n",popData);L->top--;return popData; }}int GetTop(SeqStack * L){ int topData; if(EmptyStack(L)==false)return; else{topData=L->data[L->top];printf("當(dāng)前棧頂元素為:%d \n",topData);return topData; } }int main() {SeqStack L;Initstack(&L);int popData,pushData,topData;int command;Menu();do{scanf("%d",&command);switch(command){case 1:printf("請輸入需要入棧的整數(shù):\n");scanf("%d",&pushData);Push(&L,pushData);break;case 2:popData=Pop(&L);break;case 3:Initstack(&L);printf("創(chuàng)建成功\n");break;case 4:topData=GetTop(&L);break;case 0:printf("退出成功");break;default :printf("輸入錯(cuò)誤,請重新輸入 >");break;};}while(command);return 0; }總結(jié)
以上是生活随笔為你收集整理的实现栈的基本操作(c语言)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Chrome 插件开发
- 下一篇: [算法] 求排列组合: 从n个数中任选m