数据结构栈的基本操作实现(C语言实现)

这篇博客介绍了如何使用C语言实现栈的基本操作,包括初始化、入栈、出栈、打印栈顶和栈底元素以及销毁栈。代码示例中详细展示了每个操作的实现细节,并在main函数中进行了测试。注意在操作栈时要避免混乱的指针操作以防止越界错误。
摘要由CSDN通过智能技术生成

栈的基本操作的实现
栈:是一种受限的链表只允许在同一端插入(入栈:Push)和删除(出栈:Pop),所以栈遵循先进后出的原则

栈的基本操作的实现如下:

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

typedef int ElementType;

typedef struct Node {
    ElementType element;
    struct Node *next;
} Node, *Stack;

//****************定义基本操作*********************
Stack Init_Stack(); //初始化一个头节点;

Stack Push(Stack P, ElementType e);

Stack Pop(Stack P);

void PrtStack(Stack P); //打印栈中元素;

ElementType Top(Stack P); //打印栈顶元素;

ElementType Bottom(Stack P); //打印栈底元素;

void DestroyStack(Stack P); //销毁一个栈;
//*******************#end************************

int main() {
    Stack S = Init_Stack();
    Stack P = S;

    for (int i = 0; i < 5; ++i) {
        P = Push(P, i);
    }
    printf("%d\n", Top(P));
//    PrtStack(P);
    P = Pop(P);
    printf("%d\n", Top(P));
//    PrtStack(P);
    printf("%d\n", Bottom(P));
    DestroyStack(P);
    return 0;
}

Stack Init_Stack() {
    Stack NewNode = (Stack) malloc(sizeof(Node));
    NewNode->next = NULL;
    NewNode->element = -1;
    return NewNode;
}

Stack Push(Stack P, ElementType e) {
    //P为一个指向栈顶的指针
    Stack NewNode = (Stack) malloc(sizeof(Node));
    NewNode->next = P;
    NewNode->element = e;
    P = NewNode; //S始终指向栈底,P始终指向栈顶
    return P;
}

Stack Pop(Stack P) {
    Stack TemCell = P;
    P = P->next;
    free(TemCell);
    return P;
}

void PrtStack(Stack P) {
    if (P->element == -1)
        return;
    printf("%d\n", P->element);
    PrtStack(P = P->next);
}

ElementType Top(Stack P) {
    return P->element;
}

ElementType Bottom(Stack P) {
    if (P->next->element == -1)
        return P->element;
    Bottom(P = P->next);
    return 0;
}

void DestroyStack(Stack P) {
    if (P->next == NULL) {
        printf("This stack is destroyed!!");
        return;
    }
    Stack TempCell = P;
    P = P->next;
    free(TempCell);
    DestroyStack(P);
}

错误总结:

  1. 对与一个结构体指针P,尽量使用一种统一的结构去操作,不要一会用P->next,一会用P,这样非常有能导致混乱,进而发生越界错误
  2. 在函数中如果指针没有被返回的话,是有可能造成指针并未发生实际改变,尤其是在pop操作实现的时候,很有可能导致指针并没按照我们所想移动,进而导致free()函数发生错误。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值