编写C语言程序:建立链栈,并在链栈上实现入栈和出栈操作
时间: 2024-02-01 15:13:17 浏览: 85
下面是建立链栈并实现入栈和出栈操作的C语言程序:
```c
#include<stdio.h>
#include<stdlib.h>
// 定义链栈结构体
struct node {
int data;
struct node *next;
};
// 定义链栈指针类型
typedef struct node * Stack;
// 创建空栈
Stack createStack() {
Stack s = (Stack)malloc(sizeof(struct node));
s->next = NULL;
return s;
}
// 判断是否为空栈
int isEmpty(Stack s) {
return s->next == NULL;
}
// 入栈
void push(Stack s, int value) {
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
newNode->next = s->next;
s->next = newNode;
}
// 出栈
int pop(Stack s) {
if(isEmpty(s)) {
printf("Stack is empty!\n");
return -1;
}
struct node *temp = s->next;
int data = temp->data;
s->next = temp->next;
free(temp);
return data;
}
int main() {
Stack s = createStack();
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;
}
```
程序中首先定义了链栈的结构体类型和链栈指针类型,然后通过`createStack`函数创建空栈,通过`isEmpty`函数判断栈是否为空,通过`push`函数实现入栈操作,通过`pop`函数实现出栈操作。在`main`函数中,我们创建了一个链栈`s`,依次入栈1、2、3,然后依次出栈,并打印出栈元素的值。
阅读全文
相关推荐
![](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://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.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)