温馨提示×

c语言中push函数怎么使用

小亿
156
2024-02-22 16:21:28
栏目: 编程语言

在C语言中,我们通常使用数组来模拟栈的操作,push函数用于向栈中添加元素。下面是一个简单的例子来演示push函数的使用:

#include <stdio.h>
#define MAX_SIZE 100

int stack[MAX_SIZE];
int top = -1;

void push(int element) {
    if (top >= MAX_SIZE - 1) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = element;
        printf("%d pushed to stack\n", element);
    }
}

int main() {
    push(10);
    push(20);
    push(30);

    return 0;
}

在上面的例子中,我们定义了一个名为stack的数组来模拟栈,top变量用于记录栈顶的位置。push函数接受一个整数参数element,将其添加到栈中。在main函数中,我们调用了push函数三次,将10,20和30依次添加到栈中。当栈已满时,push函数会输出"Stack Overflow"提示。

希望这个例子能帮助您理解如何在C语言中使用push函数。

0