前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C语言实现链栈相关操作

C语言实现链栈相关操作

作者头像
陈大剩博客
发布2023-03-06 09:04:31
6030
发布2023-03-06 09:04:31
举报
文章被收录于专栏:陈大剩博客专栏

栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct {
    int data;
    struct Stack *next;
} Stack;

/**
 * 初始化链表
 * @param S
 */
void InitList(Stack **S) {
    //申请头节点
    Stack *p = (Stack *) malloc(sizeof(Stack));
    if (p == NULL) {
        printf("%s函数执行,申请内存失败\n", __FUNCTION__);
    }
    *S = p;
};

/**
 * 获取输入值
 * @param list
 */
void GetInput(Stack *list) {
    Stack *temp = list;
    printf("请输入值\n");
    temp->next = NULL;
    scanf("%d", &temp->data);
}

/**
 * 创建节点
 * @param list
 */
void CreateNode(Stack **list) {
    Stack *temp = (Stack *) malloc(sizeof(Stack));
    if (temp == NULL) {
        printf("%s函数执行,申请内存失败\n", __FUNCTION__);
    }
    GetInput(temp);
    *list = temp;
}

/**
 * 入栈
 * @param S
 * @return
 */
_Bool Push(Stack *S) {
    Stack *temp = NULL;
    CreateNode(&temp);
    temp->next = S->next;
    S->next = temp;
    return true;
}

/**
 * 出栈
 * @param S
 * @return
 */
_Bool Pop(Stack *S) {
    if (S->next == NULL) {
        printf("空栈 \n");
        return false;
    }
    Stack *temp = NULL;
    temp = S->next;
    S->next = temp->next;
    free(temp);
    return true;
}

/**
 * 获取栈顶元素
 * @param S
 * @return
 */
_Bool GetTop(Stack *S) {
    if (S->next == NULL) {
        printf("空栈 \n");
        return false;
    }
    Stack *temp = NULL;
    temp = S->next;
    printf("栈顶的值为:%d \n", temp->data);
    return true;
}

/**
 * 打印栈内所有内容
 * @param list
 */
void PrintList(Stack *list) {
    Stack *temp = list;
    if (temp == NULL) {
        printf("%s函数执行,链表为空\n", __FUNCTION__);
    } else {
        while (temp->next) {
            temp = temp->next;
            printf("栈内元素的值为:%d \n", temp->data);
        }
    }
    putchar('\n');
}

int main() {
    Stack *s;
    InitList(&s);
    Push(s);
    Push(s);
    PrintList(s);
    GetTop(s);
    Pop(s);
    Pop(s);
    GetTop(s);
    Pop(s);
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档