用c语言建立链栈,并在链栈上实现入栈和出栈操作
时间: 2024-02-03 10:13:22 浏览: 11
好的,以下是用 C 语言实现链栈,包含入栈和出栈操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈结构体
typedef struct Node {
int data;
struct Node *next;
} Node, *Stack;
// 初始化栈
void init(Stack *s) {
(*s) = NULL;
}
// 判断栈是否为空
int empty(Stack s) {
return s == NULL;
}
// 入栈
void push(Stack *s, int data) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = (*s);
(*s) = p;
}
// 出栈
int pop(Stack *s) {
if (empty(*s)) {
printf("栈已空,无法出栈!\n");
return -1; // 返回一个表示出错的值,比如 -1
}
Node *p = (*s);
int data = p->data;
(*s) = p->next;
free(p);
return data;
}
int main() {
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("出栈元素:%d\n", pop(&s));
printf("出栈元素:%d\n", pop(&s));
printf("出栈元素:%d\n", pop(&s));
printf("出栈元素:%d\n", pop(&s)); // 测试栈已空的情况
return 0;
}
```
以上程序中,我们先定义了一个链栈结构体 `Node`,其中包含了数据域 `data` 和指针域 `next`。然后定义了一些函数,如 `init` 用于初始化栈,`empty` 用于判断栈是否为空,`push` 用于入栈,`pop` 用于出栈。最后在主函数中测试这些函数的功能。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)