题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <iostream>
#include <string>
using namespace std;
// 因为无法得知操作的数据量,采用链式栈的结构
typedef struct LinkedNode{
int data;
struct LinkedNode* next;
}LiStack,*Stack;
void push(Stack &S, int e) {
Stack T = (Stack)malloc(sizeof(LiStack));
T -> data = e;
T -> next = S;
S = T;
}
int pop(Stack &S) {
Stack T = S;
int res = S -> data;
S = S -> next;
free(T);
return res;
}
int top(Stack &S) {
return S -> data;
}
int main() {
// 带头结点的链式栈
Stack S = (Stack)malloc(sizeof(LiStack));
// 初始化
S -> next = NULL;
S -> data = 0;
int a;
string b;
int c;
cin >> a;
while (a >= 1) {
cin >> b;
if(b.compare("push") == 0) {
cin >> c;
}
if(b.compare("push") == 0) {
// 头插法入栈
push(S, c);
} else if(b.compare("pop") == 0) {
if(S -> next == NULL) {
cout << "error" << endl;
} else {
int res = pop(S);
cout << res << endl;
}
} else if(b.compare("top") == 0) {
if(S -> next == NULL) {
cout << "error" << endl;
} else {
int res = top(S);
cout << res << endl;
}
}
a--;
}
return 0;
}
// 64 位输出请用 printf("%lld")
查看18道真题和解析