牛客算法入门-AB1【模板】 栈

(蒟蒻第一篇博客)

磕了蛮久一道题。

描述

请你实现一个栈。

操作:

push x:将 加x\x 入栈,保证 x\x 为 int 型整数。

pop:输出栈顶,并让栈顶出栈

top:输出栈顶,栈顶不出栈

输入描述:

第一行为一个正整数 n\n ,代表操作次数。(1 \leq n \leq 100000)(1≤n≤100000)

接下来的 n\n ,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。


 

输出描述:

如果操作为push,则不输出任何东西。

如果为另外两种,若栈为空,则输出 "error“

否则按对应操作输出。

按照数据结构书上编写了基本操作函数,遇到了很多问题,大多数是在将思路转换为C语言的过程中出现的问题:

1、使用bool类型,出现的false,true在C语言中需要声明库函数<stdbool.h>,否则会报错,将源文件改为.cpp文件后,不声明库函数也不会报错。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>//使用bool型
#include<string.h>
#define MAXSIZE 100000
#define Elemtype int

//进栈
bool Push(SqStack* S, int x)
{
	if (S->top == MAXSIZE - 1)
		return false;
	else
		S->data[++S->top] = x;
	return true;
}

2、在C语言中,函数参数无法使用&符,类似数据结构书上pop函数的写法无法通过,只能通过*,指针来带回数据

//出栈
int Pop(SqStack* S) {
	if (S->top == -1)
		return -1;
	else
	{
		return S->data[S->top--];
	}
	return 0;
}

3、我原本使用的出栈函数对测试数据无法全部通过,数据太多(100000),无法一一排查,只能看了题解进行改编。原本的pop函数如下:

//出栈
bool Pop(SqStack* S, int *x) {
	if (S->top == -1)
		return false;
	else
	{
		*x=S->data[S->top--];
	}
	return true;
}

识别pop功能的代码:

else if (strcmp(str, "pop") == 0)
		{
			if (S->top == -1)
				printf("error\n");
			else {
				int* x = (int*)malloc(sizeof(int));
				Pop(S, x);
				printf( "%d\n",*x );
			}
			
		}

不知何处出了问题,改了pop函数之后,所有测试数据能全部通过。

4、通过的代码如下:

#define _CRT_SECURE_NO_WARNINGS 1
//栈的练习01

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>//使用bool型
#include<string.h>
#include<ctype.h>
#define MAXSIZE 100000
#define Elemtype int


typedef struct SqStack 
{
	int data[MAXSIZE];//存放栈中元素
	int top;//栈顶指针
}SqStack;

//初始化函数
void InitStack(SqStack *S) //*S表示栈的什么呢?
{
	S->top= -1;
}


//进栈
bool Push(SqStack* S, int x)
{
	if (S->top == MAXSIZE - 1)
		return false;
	else
		S->data[++S->top] = x;
	return true;
}

//出栈
int Pop(SqStack* S) {
	if (S->top == -1)
		return -1;
	else
	{
		return S->data[S->top--];
	}
	return 0;
}

int main()
{
	int n=0;//操作次数
	SqStack *S=(SqStack *)malloc(sizeof(SqStack));
	InitStack(S);//初始化栈
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		char str[5] = { 0 };
		int e;
		scanf("%s", str);
		if (strcmp(str, "push") == 0)
		{			
			scanf("%d", &e);
			Push(S, e);
		}
		else if (strcmp(str, "pop") == 0)
		{
			if (S->top == -1)
				printf("error\n");
			else {
				
				printf( "%d\n",Pop(S) );
			}
			
		}
		else if (strcmp(str, "top") == 0)
		{
			if (S->top == -1)
				printf("error\n");
			else
				printf("%d\n", S->data[S->top]);
		}
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值