C语言实现栈(简单明了+配图)

在栈上执行的基本操作如下:

Push:向栈顶添加一个元素
Pop:从栈顶移除一个元素
IsEmpty:检查栈是否为空
IsFull:检查栈是否满
Peek:获取顶部元素的值而不删除它

实现思路:

  1. 使用称为 TOP 的指针用于跟踪堆栈中的顶部元素。
  2. 在初始化栈的时候,我们将TOP的值设置为-1,这样我们就可以通过比较TOP == -1来判断栈是否为空。
  3. 在push一个元素时,我们增加 TOP 的值并将新元素放置在 TOP 指向的位置。(在push之前,检查堆栈是否已经满了)
  4. 在pop一个元素时,我们返回 TOP 指向的元素并减少它的值。(在pop之前,检查堆栈是否已经为空)

​​​​在这里插入图片描述

// Stack implementation in C

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

#define MAX 10

struct stack {
  int items[MAX];
  int top;
  int count;
};

typedef struct stack st;

void createStack(st *s) {
  s->top = -1;
  s->count = 0;
}

int isFull(st *s) {
  if (s->top == MAX - 1) {
    return 1;
  } else {
    return 0;
  }
}

int isEmpty(st *s) {
  if (s->top == -1) {
    return 1;
  } else {
    return 0;
  }
}

void push(st *s, int item) {
  if (isFull(s)) {
    printf("STACK FULL\n");
  } else {
    s->top++;
    s->items[s->top] = item;
    s->count++;
  }
}

int pop(st *s) {
  if (isEmpty(s)) {
    printf("STACK EMPTY\n");
  } else {
    int popped = s->items[s->top];
    s->top--;
    s->count--;
    return popped;
  }
}

void printStack(st *s) {
  for (int i = 0; i < s->count; i++) {
    printf("%d\n", s->items[i]);
  }
}

// Driver code
int main() {
  st *s = (st *)malloc(sizeof(st));

  createStack(s);

  push(s, 1);
  push(s, 2);
  push(s, 3);
  push(s, 4);

  printf("Current Stack:\n");
  printStack(s);
  printf("\n");

  printf("%d is popped out.\n", pop(s));

  printf("Current Stack:\n");
  printStack(s);
  printf("\n");

  printf("%d is popped out.\n", pop(s));

  printf("Current Stack:\n");
  printStack(s);
  printf("\n");

  push(s, 5);
  
  printf("\nAfter pushing 5 into the stack\n");
  printf("Current Stack:\n");
  printStack(s);
  printf("\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值