用c语言编写链栈依次进栈数据为 1,2,3,4,5,再全部出栈,输出出栈
时间: 2023-08-03 20:07:17 浏览: 99
C语言创建一个栈+入栈+出栈
以下是用C语言编写的链栈操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈节点
typedef struct node {
int data;
struct node *next;
} Node;
// 初始化链栈,返回栈顶指针
Node* initStack() {
Node *top = (Node*)malloc(sizeof(Node));
top->next = NULL;
return top;
}
// 判断链栈是否为空
int isEmpty(Node *top) {
return top->next == NULL;
}
// 入栈操作
void push(Node *top, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = top->next;
top->next = newNode;
}
// 出栈操作,返回出栈元素
int pop(Node *top) {
if (isEmpty(top)) {
printf("Stack is empty!\n");
return -1;
}
Node *tmp = top->next;
int data = tmp->data;
top->next = tmp->next;
free(tmp);
return data;
}
// 打印链栈中所有元素
void printStack(Node *top) {
printf("Stack elements: ");
Node *p = top->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *top = initStack();
// 依次进栈数据为 1,2,3,4,5
push(top, 1);
push(top, 2);
push(top, 3);
push(top, 4);
push(top, 5);
printStack(top);
// 全部出栈,输出出栈元素
printf("Pop elements: ");
while (!isEmpty(top)) {
printf("%d ", pop(top));
}
printf("\n");
return 0;
}
```
输出结果为:
```
Stack elements: 5 4 3 2 1
Pop elements: 5 4 3 2 1
```
阅读全文