陈大剩博客

C语言实现链栈相关操作

  • 陈大剩
  • 2021-02-07 22:36:38
  • 3325

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

#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;
}

分享到:
1

说点儿什么吧

头像

表情

本站由陈大剩博客程序搭建 | 湘ICP备2023000975号| Copyright © 2017 - 陈大剩博客 | 本站采用创作共用版权:CC BY-NC 4.0

站长统计| 文章总数[109]| 评论总数[9]| 登录用户[22]| 时间点[112]

logo

登入

社交账号登录