链栈的基本操作c语言

链栈是一种栈的实现方式,使用链表来存储栈中的元素。下面是链栈的基本操作的C语言实现:

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

// 定义链栈的结点结构
typedef struct Node {
    int data;        // 存储数据
    struct Node* next;    // 指向下一个结点的指针
} Node;

// 定义链栈的结构
typedef struct {
    Node* top;    // 栈顶指针
} Stack;

// 初始化链栈
void init(Stack* stack) {
    stack->top = NULL;
}

// 判断链栈是否为空
int isEmpty(Stack* stack) {
    return stack->top == NULL;
}

// 元素入栈
void push(Stack* stack, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = stack->top;
    stack->top = newNode;
}

// 元素出栈
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        // 栈为空时出栈操作非法
        printf("Stack is empty\n");
        return -1;
    }
    Node* tempNode = stack->top;
    int data = tempNode->data;
    stack->top = tempNode->next;
    free(tempNode);
    return data;
}

// 获取栈顶元素
int peek(Stack* stack) {
    if (isEmpty(stack)) {
        // 栈为空时获取栈顶元素非法
        printf("Stack is empty\n");
        return -1;
    }
    return stack->top->data;
}

// 打印链栈中的元素
void display(Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return;
    }
    Node* currentNode = stack->top;
    while (currentNode) {
        printf("%d ", currentNode->data);
        currentNode = currentNode->next;
    }
    printf("\n");
}

int main() {
    Stack stack;
    init(&stack);
    
    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);
    push(&stack, 4);
    
    display(&stack);    // 输出:4 3 2 1
    
    printf("Peek: %d\n", peek(&stack));    // 输出:4
    
    printf("Pop: %d\n", pop(&stack));    // 输出:4
    
    printf("Pop: %d\n", pop(&stack));    // 输出:3
    
    display(&stack);    // 输出:2 1
    
    return 0;
}

以上是链栈的基本操作的C语言实现。代码中使用结构体 Node 表示链栈的节点,Stack 表示链栈本身。链栈的基本操作包括初始化链栈、判断链栈是否为空、元素入栈、元素出栈、获取栈顶元素和打印链栈中的元素。你可以根据需要进行相应的调用和扩展。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玥沐春风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值