c语言编写一个程序实现链栈的入栈和出栈
时间: 2024-10-13 12:19:14 浏览: 76
在C语言中,链栈是一种基于链表实现的数据结构,它允许我们在栈顶添加元素(入栈)和删除元素(出栈)。下面是一个简单的链栈实现,包括了`push`(入栈)和`pop`(出栈)两个基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈节点结构体
typedef struct Node {
int data;
struct Node* next;
} StackNode;
// 初始化空栈
StackNode* createStack() {
StackNode* top = NULL;
return top;
}
// 入栈函数 - 添加元素到栈顶
void push(StackNode** top, int value) {
StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = *top;
*top = newNode;
printf("Pushed %d onto the stack.\n", value);
}
// 出栈函数 - 删除并返回栈顶元素
int pop(StackNode** top) {
if (*top == NULL) {
printf("Stack is empty.\n");
return -1; // 或者抛出异常
}
StackNode* temp = *top;
int value = temp->data;
*top = temp->next;
free(temp); // 释放已删除节点内存
printf("Popped %d from the stack.\n", value);
return value;
}
int main() {
StackNode* stack = createStack();
// 示例操作
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
while (stack != NULL) {
int poppedValue = pop(&stack);
if (poppedValue != -1) {
printf("Top element after pop: %d\n", poppedValue);
}
}
return 0;
}
```
在这个示例中,我们首先定义了一个链栈节点结构,并创建了一个空栈。然后实现了`push`和`pop`函数,其中`push`会在链首添加新节点,而`pop`则会移除并返回栈顶节点的值。在`main`函数中展示了如何使用这些操作。
阅读全文
相关推荐

















