21xrx.com
2024-09-20 00:10:12 Friday
登录
文章检索 我的文章 写文章
如何用数组和函数实现栈的功能在C语言中
2023-06-16 10:55:30 深夜i     --     --
数组 函数

栈是一个在计算机科学中非常常见的数据结构,它具有后进先出(LIFO)的特点。在C语言中,我们可以使用数组和函数来实现栈的基本功能。首先,我们需要定义一个数组来存储栈中的元素。然后,我们需要实现几个函数来操作这个数组,包括入栈、出栈、查看栈顶元素等。下面是一个使用数组和函数实现栈的示例代码。


#include

#define MAX_CAPACITY 100

int stack[MAX_CAPACITY];

int top = -1;

void push(int value) {

  if (top >= MAX_CAPACITY - 1) {

    printf("Stack overflow\n");

  } else {

    top++;

    stack[top] = value;

  }

}

int pop() {

  if (top == -1) {

    printf("Stack underflow\n");

    return -1;

  } else {

    int value = stack[top];

    top--;

    return value;

  }

}

int peek() {

  if (top == -1) {

    printf("Stack is empty\n");

    return -1;

  } else {

    return stack[top];

  }

}

int main() {

  push(3);

  push(5);

  push(9);

  printf("Current top element: %d\n", peek());

  pop();

  printf("Current top element: %d\n", peek());

  pop();

  printf("Current top element: %d\n", peek());

  push(11);

  printf("Current top element: %d\n", peek());

  return 0;

}

在这个示例中,我们使用了一个静态数组`stack`来存储栈中的元素,以及一个指向栈顶的变量`top`。`push()`函数用来将元素入栈,`pop()`函数用来将栈顶元素出栈,`peek()`函数用来查看栈顶元素。在`push()`和`pop()`函数中,我们需要对栈进行大小和空判断,避免出现栈上溢或下溢的情况。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复