题解 | #设计getMin功能的栈#
设计getMin功能的栈
https://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be
#include <stdio.h> #include <string.h> #include<stdlib.h> #define MAX_SIZE 1000000 typedef struct { int data[MAX_SIZE]; int top; } stack; int main() { int cnt, i, j, k = 0, temp, flag = 0, q; int minn = 1000001; char buf[50] = {'\0'}; char str[50] = {'\0'}; char str1[10] = "getMin"; char str2[10] = "pop"; stack* s = (stack*)malloc(sizeof(stack)); s->top = -1; scanf("%d", &cnt); getchar(); for(i = 1; i <=cnt; i++) { scanf("%[^\n]", str); getchar(); if(!strcmp(str, str2)){ s->top--; } else if(!strcmp(str, str1)) { for(q = 0; q<=s->top; q++){ if(s->data[q]<minn){ minn = s->data[q]; } } printf("%d\n", minn); minn = 1000001; } else { for(j = 0; j < strlen(str); j++) { if(str[j] == '-') { flag = 1; break; } } do { if(str[k]<'0'||str[k]>'9'){ k++; } else{ strcat(buf,&str[k]); break; } }while(str[k]!='\0'); k = 0; temp = atoi(buf); memset(buf, '\0', sizeof(buf)); temp = (flag==1 ? (0-temp) : temp); flag = 0; s->top++; s->data[s->top] = temp; } } return 0; }