题解 | #栈(模板)#

用C语言实现栈,尽可能使用面向对象思想,不得不说C语言写起来不如C++顺手

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef MAX
#define MAX 100000
#endif

typedef struct {
  int arr[MAX];
  int base;
}stack;

void pop(stack *s) {
  if (s->base == -1) {
    printf("error\n");
    return ;
  } else {
    printf("%d\n", s->arr[(s->base)--]);
  }
}

void push(stack *s, int num) {
  s->arr[++(s->base)] = num;
}

int top(stack *s) {
  if (s->base == -1) {
    printf("error\n");
    return -1;
  } else {
    return s->arr[(s->base)];
  }
}

int main(int argc, char *argv[]) {
  stack *s = (stack *)malloc(sizeof(stack));
  s->base = -1;
  
  int count = 0;
  scanf("%d", &count);
  
  char str[5];
  
  while (--count >= 0) {
    scanf("%s", str);
    
    if (!strcmp(str, "push")) {
      int tmp;
      scanf("%d", &tmp);
      push(s, tmp);
    } else if (!strcmp(str, "pop")) {
      pop(s);
    } else if (!strcmp(str, "top")) {
      int tmp = top(s);
      if (tmp != -1) {
        printf("%d\n", tmp);
      }
    }
  }
  
  return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
04-15 15:45
天杀的,早知道读完高中随便考个大专就行了
bugfree小菜狗:人家进去是国企里面的一线员工你愿意去吗和兄弟们想去坐办公室不是一个难度啊
点赞 评论 收藏
分享
点赞 评论 收藏
分享
04-13 18:10
门头沟学院 Java
dawn___:以后只用老年机
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务