顺序栈基本操作(入栈和出栈)C语言详解

本文详细介绍了C语言如何实现顺序栈的基本操作,包括入栈和出栈。通过定义顺序栈的数据结构,设置栈顶指针,并通过函数实现元素的压入和弹出。示例代码展示了从创建空栈到依次压入4个元素,再逐一弹出的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
/*
    顺序栈基本操作(入栈和出栈)C语言详解
    栈的具体实现(1)顺序栈(2)链栈
    栈的应用(1)回退 (2)框号应用问题 (3)进制转换
    顺序栈的基本操作:
    顺序表中设定一个实时指向的栈顶元素结构的变量。
    设置栈顶为top return top top初始值为-1
    入栈top +1
    出栈top -1
*/
//元素进栈
int push(int*a ,int top,int elem)
{
    a[++top] = elem;
    return top;
}
//元素出栈
int pop(int *a,int top)
{
    if(top==-1)
    {
        printf("空栈");
        return -1;
    }
    printf("出栈数据为:%d\n",a[top]);
    top--;
    return top;
}
int main()
{
    int a[100];
    int top = -1;
    top = push(a,top,1);
    top = push(a,top,2);
    top = push(a,top,3);
    top = push(a,top,4);
    top=pop(a, top);
    top=pop(a, top);
    top=pop(a, top);
    top=pop(a, top);
    top=pop(a, top);
    return 0;
}

顺序栈出栈操作可以用 C++ 语言实现,具体代码如下: ```cpp #include <iostream> using namespace std; const int MAXSIZE = 100; // 定义的最大长度 // 定义顺序栈结构体 struct SeqStack { int data[MAXSIZE]; int top; // 顶指针 }; // 初始化顺序栈 void InitStack(SeqStack &s) { s.top = -1; // 顶指针初始化为-1 } // 判断是否为空 bool IsEmpty(SeqStack s) { return s.top == -1; } // 判断是否已满 bool IsFull(SeqStack s) { return s.top == MAXSIZE - 1; } // 操作 bool Push(SeqStack &s, int x) { if (IsFull(s)) { return false; // 已满,失败 } s.top++; // 顶指针加1 s.data[s.top] = x; // 将元素x return true; // 成功 } // 出栈操作 bool Pop(SeqStack &s, int &x) { if (IsEmpty(s)) { return false; // 为空,出栈失败 } x = s.data[s.top]; // 取出栈顶元素 s.top--; // 顶指针减1 return true; // 出栈成功 } int main() { SeqStack s; InitStack(s); // 初始化 // 操作 Push(s, 1); Push(s, 2); Push(s, 3); // 出栈操作 int x; Pop(s, x); cout << "出栈的元素为:" << x << endl; Pop(s, x); cout << "出栈的元素为:" << x << endl; Pop(s, x); cout << "出栈的元素为:" << x << endl; if (Pop(s, x)) { cout << "出栈的元素为:" << x << endl; } else { cout << "为空,出栈失败!" << endl; } return 0; } ``` 以上代码中,我们定义了一个 `SeqStack` 结构体,包含一个数组 `data` 一个整型变量 `top`,其中 `top` 表示顶指针,初始化为 -1。然后我们实现了的初始化、判断是否为空或已满、出栈操作。在主函数中,我们进行了出栈的测试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值