题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> typedef struct LNode { int data; struct LNode *next; }LNode; void push(LNode *h_node, int data); int pop(LNode *h_node); int top(LNode *h_node); int main() { int num; while(scanf("%d",&num)!=EOF) { // read command char command[5]; int value; // result int result = 0; // list head LNode *h_node; h_node = (LNode *)malloc(sizeof(LNode)); for(int i=0;i<num;i++) { scanf("%s", command); if(!strcmp(command, "push")) { scanf("%d", &value); push(h_node, value); } else if(!strcmp(command, "pop")) { result = pop(h_node); if(result==0){printf("error\n");} else{printf("%d\n", result);} } else if(!strcmp(command, "top")) { result = top(h_node); if(result==0){printf("error\n");} else{printf("%d\n", result);} } } } return 0; } void push(LNode *h_node, int data) { int counter = 0; LNode *p; p = h_node; // create new node LNode *new_node; new_node = (LNode *)malloc(sizeof(LNode)); new_node->data = data; new_node->next = p->next; // add new node to list p->next = new_node; } int pop(LNode *h_node) { LNode *p; LNode *d; p = h_node; d = h_node->next; // delete the last node and reture its data int result = 0; if(d) { result = d->data; p->next = d->next; free(d); } return result; } int top(LNode *h_node) { LNode *p; int result = 0; p = h_node->next; if(p) { result = p->data; } return result; }
为了支持多用例测试,需要允许多次输出。因此,读取输入指令时,需要像20行一样添加一个循环来判断输入是否结束。注意EOF在C语言中代表-1而不是0。
#C语言代码测试通过提交不通过的解决办法#