以下是使用 C 语言实现链式栈的代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node *next; } Node; // 定义链式栈结构体 typedef struct Stack { Node *top; } Stack; // 创建一个新的节点 Node *createNode(int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; return newNode; } // 创建一个空的链式栈 Stack *createStack() { Stack *stack = (Stack *)malloc(sizeof(Stack)); stack->top = NULL; return stack; } // 判断链式栈是否为空 int isEmpty(Stack *stack) { return (stack->top == NULL); } // 入栈操作 void push(Stack *stack, int data) { Node *newNode = createNode(data); newNode->next = stack->top; stack->top = newNode; } // 出栈操作 int pop(Stack *stack) { if (isEmpty(stack)) { printf("Stack is empty!\n"); return -1; } int data = stack->top->data; Node *temp = stack->top; stack->top = stack->top->next; free(temp); return data; } // 打印链式栈 void printStack(Stack *stack) { Node *current = stack->top; while (current!= NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } int main() { Stack *stack = createStack(); int length = 3; int elements[] = {1, 2, 4}; // 入栈操作 for (int i = 0; i < length; i++) { push(stack, elements[i]); } printf("入栈后: "); printStack(stack); // 出栈操作 pop(stack); printf("出栈后: "); printStack(stack); return 0; } ``` 1. 注意内存的分配和释放,避免内存泄漏。 2. 处理入栈和出栈时,要确保操作的合法性,比如栈为空时不能出栈。 3. 代码中的打印输出格式可以根据实际需求进行调整。 [2024-12-21 20:34:29 | AI写代码神器 | 592点数解答]