6-栈的链式存储类型

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

typedef int ElemType;

/*栈的链式存储类型*/
typedef struct  StackNode{
    /*数据域*/
    ElemType  data;
    /*指针域*/
    struct  StackNode *next;
} StackNode,*LinkStack; /*栈类型定义*/


/**
 *  在栈顶插入元素e
 * @param S   *S 是栈顶指针
 * @param e
 */
void Push(LinkStack *S, ElemType e) {
    // 生成新的节点
    StackNode *p = (StackNode *) malloc(sizeof(StackNode));
    if (p == NULL) {
        printf("内存分配失败!\n");
        exit(1);
    }
    p->data = e;     // 设置新节点的数据
    p->next = *S;    // 将新节点的 next 指向当前的栈顶节点
    *S = p;          // 更新栈顶指针,使其指向新节点
}
/* 出栈操作 */
bool Pop(LinkStack *S, ElemType *e) {
    /*头节点 空*/
    if (*S == NULL) {
        return false; /* 栈空,不能出栈 */
    }
    StackNode *p = *S; /* 临时指针指向栈顶节点 */
    *e = p->data;      /* 将栈顶元素赋值给e */
    *S = p->next;      /* 更新栈顶指针 */
    free(p);           /* 释放栈顶节点 */
    return true;
}


int main() {


    return 0;
}

posted @ 2024-07-10 17:24  成强  阅读(3)  评论(0编辑  收藏  举报