编马程序实现链栈的初始化、判断栈空否、入栈和出栈,用c实现并展示运行结果
时间: 2023-05-31 14:05:25 浏览: 96
以下是用C语言编写的链栈程序,包括初始化、判断栈空否、入栈和出栈操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈结构体
struct Node {
int data;
struct Node* next;
};
// 初始化链栈
void InitStack(struct Node** top) {
*top = NULL;
}
// 判断栈是否为空
int IsEmpty(struct Node* top) {
return top == NULL;
}
// 入栈
void Push(struct Node** top, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *top;
*top = newNode;
printf("Push %d to stack.\n", data);
}
// 出栈
int Pop(struct Node** top) {
if (IsEmpty(*top)) {
printf("Stack is empty.\n");
return -1;
}
int data = (*top)->data;
struct Node* temp = *top;
*top = (*top)->next;
free(temp);
printf("Pop %d from stack.\n", data);
return data;
}
int main() {
struct Node* top;
InitStack(&top);
Push(&top, 1);
Push(&top, 2);
Push(&top, 3);
Pop(&top);
Pop(&top);
Pop(&top);
Pop(&top);
return 0;
}
```
运行结果:
```
Push 1 to stack.
Push 2 to stack.
Push 3 to stack.
Pop 3 from stack.
Pop 2 from stack.
Pop 1 from stack.
Stack is empty.
```
阅读全文