数据结构--栈(不带头结点的链表实现)

目录

1、准备工作

2、入栈

3 、获取栈顶元素

4、出栈

5、判断栈空

6、打印

7、完整代码


1、准备工作

/*
类比汉诺塔 ,最上面的叫栈顶,最下面的叫栈底,每次只能从最上面拿,即 后进的先出 (LIFO)
*/

typedef int ElemTYpe;

typedef struct SNode{
    struct SNode* next;
    ElemTYpe data;
}SNode,*SList;

2、入栈

void Push(ElemTYpe e,SList *S){
    SNode *tmp = (SNode *) malloc(sizeof(SNode));
    tmp->data = e;
    tmp->next = *S;
    *S = tmp;
    printf("%d入栈\n",tmp->data);
}

3 、获取栈顶元素

ElemTYpe Top(SList S){

    if(S == NULL){
        printf("栈为空,无法获取栈顶元素\n");
        return 0;
    }
    else{
        return S->data;
    }
}

4、出栈

void Pop(SList *S){
    SNode *tmp;
    tmp = *S;
    if(tmp == NULL){
        printf("栈为空\n");
        return;
    }
    *S = (*S)->next;
    printf("%d出栈\n",tmp->data);
    free(tmp);
}

5、判断栈空

int IsEmpty(SList S){
    if(S == NULL)
        return 1;
    else
    return 0;
}

6、打印

//传进来后S只是局部变量
void PrintList(SList S){
    while (S != NULL){
        printf("%d ",S->data);
        S = S->next;
    }
    printf("\n");
}

7、完整代码

#include <stdio.h>
#include <stdlib.h>

typedef int ElemTYpe;

typedef struct SNode{
    struct SNode* next;
    ElemTYpe data;
}SNode,*SList;

//压栈
void Push(ElemTYpe e,SList *S);
//获取栈顶元素
ElemTYpe Top(SList S);
//出栈
void Pop(SList *S);
//判断栈空
int IsEmpty(SList S);
//打印
void PrintList(SList S);

int main() {
    SList S = NULL;
    ElemTYpe e = 0;

    for(int i = 1;i<6;i++){
        e++;
        Push(e,&S);
    }
    PrintList(S);

    for(int i = 1;i<3;i++){
        Pop(&S);
    }
    PrintList(S);
    printf("栈顶元素为 %d\n", Top(S));
    printf("栈的状态:%d (1表示为空)\n", IsEmpty(S));
    return 0;
}

void Push(ElemTYpe e,SList *S){
    SNode *tmp = (SNode *) malloc(sizeof(SNode));
    tmp->data = e;
    tmp->next = *S;
    *S = tmp;
    printf("%d入栈\n",tmp->data);
}

ElemTYpe Top(SList S){

    if(S == NULL){
        printf("栈为空,无法获取栈顶元素\n");
        return 0;
    }
    else{
        return S->data;
    }
}

int IsEmpty(SList S){
    if(S == NULL)
        return 1;
    else
    return 0;
}

void Pop(SList *S){
    SNode *tmp;
    tmp = *S;
    if(tmp == NULL){
        printf("无法出栈,栈为空\n");
        return;
    }
    *S = (*S)->next;
    printf("%d出栈\n",tmp->data);
    free(tmp);
}

void PrintList(SList S){
    while (S != NULL){
        printf("%d ",S->data);
        S = S->next;
    }
    printf("\n");
}

 

封面来自百度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值