链栈实现

本文介绍了一种链式栈的数据结构实现方法,并通过具体的C++代码示例展示了如何初始化链式栈、判断栈是否为空、进行入栈与出栈操作等基本功能。最后通过一个完整的程序实例演示了链式栈的应用。

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

#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;
#define TRUE 1
#define FALSE 0
typedef int ElemType;

typedef struct node
{
    ElemType data;
    struct node *next;
}StackNode, *LinkStack;

void InitStack(LinkStack top)
{
    top->next=NULL;
}

int IsEmpty(LinkStack top)
{
    if(top->next==NULL)
        return TRUE;
    return FALSE;
}

int Push(LinkStack top, ElemType e)
{
    StackNode *temp;
    temp=(LinkStack)malloc(sizeof(StackNode));
    if(temp==NULL) return FALSE;
    temp->data=e;
    temp->next=top->next;
    top->next=temp;
    return TRUE;
}

int Pop(LinkStack top, ElemType *e)
{
    if(IsEmpty(top)) return FALSE;
    StackNode *temp=top->next;
    *e=temp->data;
    top->next=temp->next;
    free(temp);

    return TRUE;
}

void GetTop(LinkStack top, ElemType *e)
{
    *e=top->next->data;
}

int main()
{
    LinkStack s;
    s=(LinkStack)malloc(sizeof(StackNode));
    InitStack(s);
    for(int i=0; i<10; i++)
        Push(s, i);
    int ans;
    while(!IsEmpty(s))
    {
        Pop(s, &ans);
        printf("%d ", ans);
    }
    printf("\n");
    return 0;
}

 

转载于:https://www.cnblogs.com/9968jie/p/5970882.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值