#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
typedef struct Stack {
int *elements;
int max_size, top_index;
}Stack;
void init(Stack *s, int length_input) {
s->elements = (int *)malloc(sizeof(int) * length_input);
s->max_size = length_input;
s->top_index = -1;
}
int push(Stack *s, int element) {
if (s->top_index >= s->max_size - 1) {
return ERROR;
}
s->top_index++;
s->elements[s->top_index] = element;
return OK;
}
int pop(Stack *s) {
if (s->top_index < 0) {
return ERROR;
}
s->top_index--;
return OK;
}
// 請(qǐng)?jiān)谙旅鎸?shí)現(xiàn)輸出棧頂函數(shù) top
int top(Stack *s){
return s->elements[s->top_index];
}
void clear(Stack *s) {
free(s->elements);
free(s);
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
Stack *stack = (Stack *)malloc(sizeof(Stack));
init(stack, n);
for (int i = 1; i <= m; i++) {
int opr;
scanf("%d", &opr);
if (opr == 0) {
int element;
scanf("%d", &element);
if (push(stack, element)) {
printf("push success!\n");
} else {
printf("push failed!\n");
}
} else if (opr == 1) {
if (pop(stack)) {
printf("pop success!\n");
} else {
printf("pop failed!\n");
}
}
else if(opr == 2){
printf("%d\n",top(stack));
}
}
clear(stack);
return 0;
}
棧的操作
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- #include #include<windows.h> #define MAXSIZE 100 typedef ...
- OpenGL中矩陣堆棧的頻繁壓棧和出棧操作往往是入門時(shí)最大的門檻,也是最容易造成困惑的地方,今天我們來詳細(xì)理解一下...
- 題目: 一個(gè)棧依次壓入 1、2、3、4、5,那么從棧頂?shù)綏5追謩e為5、4、3、2、1.將這個(gè)棧轉(zhuǎn)置后,從棧頂?shù)綏5?..
- 本題來自程序員代碼面試指南 題目 一個(gè)棧依次壓入1、2、3、4、5,那么從棧頂?shù)綏5追謩e為5、4、3、2、1。將這...
- 一個(gè)棧依次壓入1、2、3、4、5,那么從棧頂?shù)綏5追謩e為5、4、3、2、1。將這個(gè)棧轉(zhuǎn)置后,從棧頂?shù)綏5诪?、2、...