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

    科技2026-01-19  11

    栈的基本操作的实现 栈:是一种受限的链表只允许在同一端插入(入栈: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); }

    错误总结:

    对与一个结构体指针P,尽量使用一种统一的结构去操作,不要一会用P->next,一会用P,这样非常有能导致混乱,进而发生越界错误在函数中如果指针没有被返回的话,是有可能造成指针并未发生实际改变,尤其是在pop操作实现的时候,很有可能导致指针并没按照我们所想移动,进而导致free()函数发生错误。
    Processed: 0.013, SQL: 9