链栈

#include<bits/stdc++.h>
using namespace std;

struct sta{
    int data;
    sta *next;
};

void sta_creat(sta *&s){    //构造栈
    s = NULL;
}

void sta_push(sta *&s,int x){   //压栈
    sta *p = new sta;
    p->data = x;
    p->next = s;
    s = p;
}

void sta_top(sta *&s){  //栈顶元素
    if(s)
        cout<<s->data<<endl;
}

void sta_pop(sta *&s){  //弹栈顶元素
    if(s){
        sta *p = s;
        s = s->next;
        free(p);
    }
}

int main(){
    sta *s;
    sta_creat(s);
    cout<<"请输入入栈的元素个数:"<<endl;
    int n,m;
    cin>>n;
    cout<<"请输入"<<n<<"个元素"<<endl;
    while(n--){
        cin>>m;
        sta_push(s,m);
    }
    cout<<"栈顶元素为:"<<endl;
    sta_top(s);
    cout<<"弹栈一个元素后,栈顶元素为:"<<endl;
    sta_pop(s);
    sta_top(s);
    return 0;
}

链式栈_简单操作_C语言

该视频中的代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
struct node
{
    char data;
    struct node *next;
};
typedef struct node LStackNode;
typedef struct node *LinkStack;

void InitStack(LinkStack *top)//初始化链栈
{
    if((*top=(LinkStack)malloc(sizeof(LStackNode))) == NULL)
        exit(-1);
    (*top)->next = NULL;
}

int StackEmpty(LinkStack top)//判断链栈是否为空
{
    if(top->next == NULL)
        return 1;
    else
        return 0;
}

int PushStack(LinkStack top, char e)//进栈操作
{
    LStackNode *p;
    if((p = (LStackNode*)malloc(sizeof(LStackNode))) == NULL) {
        printf("内存分配失败!\n");
        exit(-1);
    }
    p->data = e;
    p->next = top->next;
    top->next = p;
    return 1;
}

int PopStack(LinkStack top, char *e)//出栈操作
{
    LStackNode *p;
    p = top->next;

    top->next = p->next;
    *e = p->data;
    free(p);
    return 1;
}

int GetTop(LinkStack top, char *e)//取栈顶元素
{
    LStackNode *p;
    p = top->next;
    if(!p) {
        printf("已是空栈!\n");
        return -1;
    }
    *e = p->data;
    return 1;
}

int StackLength(LinkStack top)//求链栈长度
{
    LStackNode *p;
    int cnt = 0;
    p = top;
    while(p->next != NULL) {
        p = p->next;
        cnt++;
    }
    return cnt;
}

void DestroyStack(LinkStack top)//销毁链栈
{
    LStackNode *p, *q;
    p = top;
    while(!p) {
        q = p;
        p = p->next;
        free(q);
    }
}

int main()
{
    LinkStack S;
    LStackNode *s;
    char ch[50], e, *p;
    InitStack(&S);
    printf("请输入进栈的字符:\n");
    gets(ch);//gets函数可以接受字符串,最大是49个字符,最后还有一个啥0(没听懂说的啥)
    p = &ch[0];//直接用ch也行
    while(*p) {
        PushStack(S, *p);
        p++;
    }
    printf("当前栈顶元素是:");
    GetTop(S, &e);
    printf("%4c\n", e);
    printf("当前栈中的元素个数为:%d\n", StackLength(S));
    printf("元素的出栈顺序为:");
    while(!StackEmpty(S)) {
        PopStack(S, &e);
        printf("%4c", e);
    }
    printf("\n");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值