链表实现栈、入栈、出栈、栈的长度、销毁栈、清空栈

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define SIZE 10
// 数据域
typedef struct LData {
    int c;  // 常数
} LData;


// 单链表
typedef struct SNode {
    LData data; //数据域
    struct SNode *next;
} SNode;

// 初始化栈
SNode *InitStack(){
    SNode *s;
    s = (SNode *) malloc(SIZE* sizeof(SNode));
    s->next = NULL;
    return s;
}

//入栈
void push(SNode **s, int e){  // 头结点为栈顶
    if((*s) == NULL){
        printf("栈不存在\n");
    }
    SNode *p; // 创建新节点,作为头结点
    p = (SNode *) malloc(sizeof(SNode));
    p->data.c = e; // 给新节点赋值
    p->next = (*s); // 新节点的下一个就是原头结点的下一个
    (*s) = p; // 将新节点的地址给原头结点
}
// 出栈
void pop(SNode **s){
    if((*s)->next == NULL){
        printf("pop栈为空\n");
        return;
    }
    SNode *p;
    p = (*s); // p保存的是头结点
    printf("出栈元素为:%d\n", (*s)->data.c);
    (*s) = p->next; // 将头结点的下一个节点作为头结点
    free(p); // 释放出栈节点
}

// 清空栈
void clearStack(SNode **s){
    if((*s)->next == NULL){
        printf("clearStack栈为空\n");
        return;
    }
    SNode *p;
    while ((*s)->next != NULL){
        p = (*s);
        (*s) = (*s)->next;
        free(p);
    }
    printf("已清空\n");
}

// 销毁栈
void destroyStack(SNode **s){
    if((*s) == NULL){
        printf("destroyStack栈为空\n");
        return;
    }
    SNode *p;
    while ((*s)->next != NULL){
        p = (*s);
        (*s) = p->next;
        free(p);
    }
    (*s) = (*s)->next;
    free((*s));
    printf("已销毁\n");
}

//获取栈的长度
void getStackLength(SNode **s){
    if((*s) == NULL){
        printf("栈为空\n");
        return;
    }
    int count = 0;
    SNode *p;
    p = (*s);
    while (p->next != NULL){
        count++;
        p = p->next;
    }
    printf("栈的长度为:%d\n", count);
}

int main() {
    //测试
    SNode *s;
    s = InitStack();
    push(&s, 1);
    push(&s, 2);
    push(&s, 3);
    push(&s, 4);
    getStackLength(&s);
    pop(&s);
    pop(&s);
    clearStack(&s);
    pop(&s);
    pop(&s);
    destroyStack(&s);
    push(&s, 4);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值