用c语言编写链栈依次进栈数据为 1,2,3,4,5,再全部出栈,输出入栈和出栈结果
时间: 2023-08-03 11:07:18 浏览: 117
shunxubiao.rar_栈的顺序表_顺序栈,出栈
以下是用C语言编写的链栈代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈节点结构体
typedef struct StackNode {
int data;
struct StackNode *next;
} StackNode;
// 定义链栈结构体
typedef struct LinkStack {
StackNode *top;
int count;
} LinkStack;
// 初始化链栈
void InitStack(LinkStack *s) {
s->top = NULL;
s->count = 0;
}
// 判断链栈是否为空
int IsEmpty(LinkStack *s) {
return s->count == 0;
}
// 入栈操作
void Push(LinkStack *s, int data) {
StackNode *node = (StackNode*)malloc(sizeof(StackNode));
node->data = data;
node->next = s->top;
s->top = node;
s->count++;
}
// 出栈操作
int Pop(LinkStack *s) {
if (IsEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
StackNode *node = s->top;
int data = node->data;
s->top = node->next;
free(node);
s->count--;
return data;
}
// 遍历链栈
void TraverseStack(LinkStack *s) {
StackNode *p = s->top;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkStack s;
InitStack(&s);
// 依次进栈数据为1,2,3,4,5
Push(&s, 1);
Push(&s, 2);
Push(&s, 3);
Push(&s, 4);
Push(&s, 5);
printf("入栈结果:");
TraverseStack(&s);
// 全部出栈
printf("出栈结果:");
while (!IsEmpty(&s)) {
printf("%d ", Pop(&s));
}
printf("\n");
return 0;
}
```
运行结果:
```
入栈结果:5 4 3 2 1
出栈结果:5 4 3 2 1
```
阅读全文