#include <stdio.h> #include <stdlib.h> // 链式栈节点的定义 typedef struct StackNode { int data; struct StackNode* next; } StackNode; // 链式栈的定义 typedef struct { StackNode* top; // 栈顶指针 } LinkedStack; // 初始化链式栈 void InitStack(LinkedStack* stack) { stack->top = NULL; } // 判断栈是否为空 int IsEmpty(LinkedStack* stack) { return stack->top == NULL; } // 入栈 void Push(LinkedStack* stack, int data) { StackNode* newNode = (StackNode*)malloc(sizeof(StackNode)); if (newNode == NULL) { printf("内存分配失败\n"); exit(EXIT_FAILURE); } newNode->data = data; newNode->next = stack->top; stack->top = newNode; } // 出栈 int Pop(LinkedStack* stack, int* data) { if (IsEmpty(stack)) { printf("栈为空,无法出栈\n"); return 0; } StackNode* topNode = stack->top; *data = topNode->data; stack->top = topNode->next; free(topNode); return 1; } // 获取栈顶元素 int GetTop(LinkedStack* stack, int* data) { if (IsEmpty(stack)) { printf("栈为空,无法获取栈顶元素\n"); return 0; } *data = stack->top->data; return 1; } // 销毁链式栈 void DestroyStack(LinkedStack* stack) { while (!IsEmpty(stack)) { int data; Pop(stack, &data); } } int main() { LinkedStack stack; InitStack(&stack); // 入栈操作 Push(&stack, 1); Push(&stack, 2); Push(&stack, 3); // 出栈操作 int data; Pop(&stack, &data); printf("出栈元素:%d\n", data); // 获取栈顶元素 GetTop(&stack, &data); printf("栈顶元素:%d\n", data); // 销毁链式栈 DestroyStack(&stack); return 0; }
标签:,int,top,LinkedStack,StackNode,data,stack From: https://www.cnblogs.com/muzhaodi/p/17832829.html