要求编写功能函数实现堆栈的定义,基于链栈:按用户要求输入元素,编写进栈函数push();编写出栈函数pop();编写判断栈满和栈空的函数 ;遍历栈,并输出元素;输入数据实现十进制到二进制的转换。c语言实现完整代码,并给出算法流程
时间: 2024-05-31 11:08:05 浏览: 8
算法流程:
1. 定义链栈节点结构体,包含数据域和指向下一节点的指针
2. 定义栈顶指针,初始值为NULL
3. 实现进栈函数push(),新建节点,将数据存入节点的数据域,将节点插入栈顶,更新栈顶指针
4. 实现出栈函数pop(),获取栈顶节点数据,删除栈顶节点,更新栈顶指针,返回节点数据
5. 实现判断栈满和栈空的函数,链栈不会满,只需要判断栈顶指针是否为NULL即可
6. 遍历栈,从栈顶开始遍历,输出每个节点的数据
7. 实现十进制到二进制的转换,使用进栈函数将余数压入栈中,直到商为0,然后弹出栈中的元素即可得到二进制数
完整代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链栈节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 定义栈顶指针,初始值为NULL
Node *top = NULL;
// 进栈函数
void push(int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = top;
top = node;
}
// 出栈函数
int pop() {
if (top == NULL) {
printf("Stack is empty.\n");
return -1;
}
int data = top->data;
Node *node = top;
top = top->next;
free(node);
return data;
}
// 判断栈空函数
int isEmpty() {
return top == NULL;
}
// 遍历栈函数
void traverse() {
Node *node = top;
printf("Stack: ");
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// 十进制到二进制转换函数
void decimalToBinary(int decimal) {
while (decimal != 0) {
int remainder = decimal % 2;
push(remainder);
decimal /= 2;
}
printf("Binary: ");
while (!isEmpty()) {
int binary = pop();
printf("%d", binary);
}
printf("\n");
}
int main() {
// 进栈
push(1);
push(2);
push(3);
traverse();
// 出栈
int data = pop();
printf("Pop: %d\n", data);
traverse();
// 判断栈空
if (isEmpty()) {
printf("Stack is empty.\n");
} else {
printf("Stack is not empty.\n");
}
// 十进制到二进制转换
decimalToBinary(10);
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)