要求编写功能函数实现堆栈的定义,基于链栈:按用户要求输入元素,编写进栈函数push();编写出栈函数pop();编写判断栈满和栈空的函数 ;遍历栈,并输出元素;输入数据实现十进制到二进制的转换。c语言实现完整代码,并给出算法流程
时间: 2024-05-29 13:11:55 浏览: 7
算法流程:
1. 定义链栈结构体,包含元素值和指向下一个元素的指针。
2. 定义栈顶指针,并初始化为NULL。
3. 定义入栈函数push(),按照用户输入的元素值创建新的节点,并将栈顶指针指向该节点。
4. 定义出栈函数pop(),判断栈是否为空,如果为空则输出提示信息;否则将栈顶指针指向下一个节点,释放原来的节点。
5. 定义判断栈空函数isEmpty(),如果栈顶指针为空则返回1,否则返回0。
6. 定义遍历栈函数traverse(),从栈顶开始依次输出每个节点的元素值。
7. 定义十进制转二进制函数decToBin(),将十进制数不断除以2,将余数入栈,直到商为0,再依次出栈得到二进制数。
8. 主函数中调用各个函数实现功能。
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
// 链栈结构体
struct Node {
int data;
struct Node* next;
};
// 栈顶指针
struct Node* top = NULL;
// 入栈函数
void push(int val) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = top;
top = newNode;
}
// 出栈函数
void pop() {
if (isEmpty()) {
printf("栈已空,无法出栈!\n");
} else {
struct Node* temp = top;
top = top->next;
printf("出栈元素:%d\n", temp->data);
free(temp);
}
}
// 判断栈空函数
int isEmpty() {
return top == NULL;
}
// 遍历栈函数
void traverse() {
if (isEmpty()) {
printf("栈为空!\n");
} else {
struct Node* temp = top;
printf("栈元素如下:\n");
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
}
}
// 十进制转二进制函数
void decToBin(int decimal) {
while (decimal != 0) {
push(decimal % 2);
decimal /= 2;
}
printf("二进制数为:");
while (!isEmpty()) {
printf("%d", top->data);
pop();
}
printf("\n");
}
int main() {
int choice, val;
printf("1. 入栈\n");
printf("2. 出栈\n");
printf("3. 判断栈空\n");
printf("4. 遍历栈\n");
printf("5. 十进制数转二进制数\n");
printf("0. 退出程序\n");
do {
printf("请输入操作编号:");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入入栈元素:");
scanf("%d", &val);
push(val);
break;
case 2:
pop();
break;
case 3:
if (isEmpty()) {
printf("栈为空!\n");
} else {
printf("栈不为空!\n");
}
break;
case 4:
traverse();
break;
case 5:
printf("请输入十进制数:");
scanf("%d", &val);
decToBin(val);
break;
case 0:
printf("程序已退出!\n");
break;
default:
printf("输入错误,请重新输入!\n");
break;
}
} while (choice != 0);
return 0;
}
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)