前言
- 个人推荐在牛客网刷题(点击可以跳转),主要它登陆后会保存刷题记录进度,重新登录时写过的题目代码不会丢失。
- 个人刷题练习系列专栏:个人CSDN牛客刷题专栏。 牛客数据结构题目位置如下:
问题描述:
请你实现一个栈。
操作:
push x:将 加x入栈,保证 x为 int 型整数。
pop:输出栈顶,并让栈顶出栈
top:输出栈顶,栈顶不出栈
输入描述:
第一行为一个正整数 n ,代表操作次数。(1≤n≤100000)
接下来的 n ,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。
输出描述:
如果操作为push,则不输出任何东西。
如果为另外两种,若栈为空,则输出 "error“
否则按对应操作输出。
举例:
//输入:
6
push 1
pop
top
push 2
push 3
pop
//输出:
1
error
3
代码结果:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
typedef struct Node { //定义数据结构,包含数据域域next域
int data;//data域
struct Node* next;//next指针域
} Node;
Node* initList() { //初始化头节点
Node* Stack = (Node*)malloc(sizeof(Node)); //开辟空间,新建节点
Stack->data = 0; //栈默认个数为0
Stack->next = NULL; //栈为空,故头节点next域指向空
return Stack;
}
bool isEmpty(Node* Stack) { //检查栈是否为空
if (Stack->data == 0 || Stack->next == NULL) return 0; //为空返回0
else return 1;//不为空返回1
}
int top(Node* Stack) { //输出栈顶,栈顶不出栈
if (isEmpty(Stack) == 0)
return -1;//栈空,输出栈顶错误
else
return Stack->next->data;//输出栈顶
}
int pop(Node* Stack) { //输出栈顶,并让栈顶出栈
if (isEmpty(Stack) == 0) return -1; //栈空,出栈错误
else {
Stack->data--;//出栈导致栈元素个数减一
Node* node =
Stack->next; //新建结点存栈顶元素,用于调整链表顺序后使用
int n = Stack->next->data; //新建遍历存储栈顶值,用于输出使用
Stack->next = Stack->next->next; //调整链表顺序,删除栈顶,
free(node);//释放栈顶节点
return n;//输出栈顶
}
}
void push(Node* Stack, int data) { //入栈
Node* node = (Node*)malloc(sizeof(Node));//开辟空间,新建节点
node->data = data;//data给到新建节点的数据域
node->next =
Stack->next; //新建节点插入头节点与旧的栈顶节点之间,即放在栈顶
Stack->next = node; //续上
Stack->data++;//入栈导致栈元素个数加一
}
int main() {
Node* Stack = initList(); //初始化头节点,创捷栈
int n = 0;
scanf("%d", &n);
while (n--) {
char* str=(char*)malloc(1*sizeof(char));//VScode中char* str;调试正确,牛客中必须申请堆内存才能正确提交,暂时没弄懂
scanf("%s", str);
if (!strcmp(str, "push")) {
int num = 0;
scanf("%d", &num);
push(Stack, num);
continue;//continue作用为结束本次循环
//break可以跳出“循环体”,还可以跳出switch
}
if (!strcmp(str, "pop")) {
int num1 = pop(Stack);
if (num1 == -1)
printf("error\n");
else printf("%d\n", num1);
continue;
}
if (!strcmp(str, "top")) {
int num2 = top(Stack);
if (num2 == -1)
printf("error\n");
else printf("%d\n", num2);
continue;
}
}
}
结束语
- 以上就是有效括号序列的内容。可以在牛客尝试刷几道单链表题目来练习实践。牛客网刷题(点击可以跳转),可以尝试注册使用。