C语言建立链栈,根据输入的栈中元素个数n和各元素值建立一个链栈,并输出栈中各元素值。
时间: 2024-02-03 17:13:59 浏览: 37
下面是C语言建立链栈的示例代码,可以根据输入的栈中元素个数n和各元素值建立一个链栈,并输出栈中各元素值:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node, *Stack;
// 初始化栈
void initStack(Stack *s) {
*s = NULL;
}
// 判断栈是否为空
int isEmpty(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) {
int data;
Node *p;
if (isEmpty(*s)) {
printf("Stack is empty.\n");
exit(1);
}
data = (*s)->data;
p = *s;
*s = (*s)->next;
free(p);
return data;
}
// 获取栈顶元素
int getTop(Stack s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data;
}
int main() {
Stack s;
initStack(&s);
int n, data;
printf("Enter the number of elements in the stack: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &data);
push(&s, data);
}
printf("The elements in the stack are: ");
while (!isEmpty(s)) {
printf("%d ", pop(&s));
}
printf("\n");
return 0;
}
```
运行示例:
```
Enter the number of elements in the stack: 5
Enter the elements: 1 2 3 4 5
The elements in the stack are: 5 4 3 2 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)