题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <vector> using namespace std; //结点结构体 typedef int DataType; typedef struct Node { DataType data; struct Node* next; }Node; typedef struct Node* LinkStack; //创建带头结点的链栈 LinkStack CreateStack() { LinkStack top = (Node*)malloc(sizeof(Node)); top->next = NULL; return top; } //链栈判空 int isNullStack(LinkStack st) { return st->next == NULL; } //入栈 void push(LinkStack* top, DataType data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = (*top)->next; (*top)->next = newNode; } //出栈 int pop(LinkStack* top) { int ret; if (isNullStack(*top)) return 0; ret = (*top)->next->data; Node* temp; temp = *top; *top = (*top)->next; free(temp); return ret; } //取栈顶元素 int top(LinkStack* top) { if (isNullStack(*top)) return 0; return (*top)->next->data; } int main() { LinkStack mystack = CreateStack(); vector<int>ret; int data; int n; char op[256] = { 0 }; scanf("%d",&n); for (int i = 0; i < n; i++) { cin >> op; if (!strcmp(op, "push")) { scanf("%d", &data); push(&mystack, data); } if (!strcmp(op, "pop")) ret.push_back(pop(&mystack)); if (!strcmp(op, "top")) ret.push_back(top(&mystack)); } //输出结果 for (int i = 0; i < ret.size(); i++) { if (ret[i] == 0) cout << "error" << endl; else cout << ret[i] << endl; } }