题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct StackNode { int data; struct StackNode* next; }StackNode; StackNode* initStack() { StackNode* S = (StackNode*)malloc(sizeof(StackNode)); S->data = 0; S->next = NULL; return S; } int isEmpty(StackNode* S) { if (S->data == 0 || S->next == NULL) return 1; else return 0; } void push(StackNode* S, int data) { StackNode* node = (StackNode*)malloc(sizeof(StackNode)); node->data = data; node->next = S->next; S->next = node; S->data ++ ; } void pop(StackNode* S) { if (isEmpty(S)) printf("error\n"); else { StackNode* p = S->next; printf("%d\n", S->next->data); S->next = p->next; //free(p); S->data -- ; } } void top(StackNode* S) { if (isEmpty(S)) printf("error\n"); else printf("%d\n", S->next->data); } int main() { StackNode* S = initStack(); int n; scanf("%d", &n); char s[5]; while (n -- ) { int x; scanf("%s %d", s, &x); if (strcmp(s, "push") == 0) push(S, x); if (strcmp(s, "top") == 0) top(S); if (strcmp(s, "pop") == 0) pop(S); } return 0; }