作业:利用链栈实现十进制向二进制、八进制、十六进制的转换。、
代码如下:
main.c
#include "main.h"
int main(int argc, char const *argv[])
{
Stacklink top = CreateLink();
int n;
if (top == NULL)
{
printf("\n链栈申请堆区空间失败!\n");
return -1;
}
printf("\n<----------------------链栈实现进制转换---------------------->\n");
printf("请输入待转换的十进制整数:");
scanf("%d",&n);
//十进制 ==> 二进制
int a = n;
while (a > 0)
{
LinkStackPush(top,a%2);
a = a / 2;
}
printf("十进制 ==> 二进制:0b");
LinkStackShow(top);
while(top->next != NULL)
{
LinkStackPop(top);
}
//十进制 ==> 八进制
int b = n;
while (b > 0)
{
LinkStackPush(top,b%8);
b = b / 8;
}
printf("十进制 ==> 八进制:0");
LinkStackShow(top);
while(top->next != NULL)
{
LinkStackPop(top);
}
//十进制 ==> 十六进制
int c = n;
while (c > 0)
{
LinkStackPush(top,c%16);
c = c / 16;
}
printf("十进制 ==> 十六进制:0x");
while (top->next != NULL)
{
int num = LinkStackPop(top);
if(num>=0 && num<10)
printf("%d",num);
else if (num == 10)
printf("a");
else if (num == 11)
printf("b");
else if (num == 12)
printf("c");
else if (num == 13)
printf("d");
else if (num == 14)
printf("e");
else if (num == 15)
printf("f");
}
printf("\n");
return 0;
}
main.h
#ifndef __MAIN_H
#define __MAIN_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int datatype;
typedef struct Node
{
union
{
int len;
datatype data;
};
struct Node *next;
}*Stacklink;
Stacklink CreateLink(); //为链栈申请堆区空间
int LinkStackPush(Stacklink top,datatype e); //压栈
void LinkStackShow(Stacklink top); //遍历输出链栈
int LinkStackPop(Stacklink top);
Stacklink Stacklink_Free(Stacklink top);
#endif // !__MAIN_H
stacklink.c
#include "main.h"
/**
* @brief 为链栈申请堆区空间
*
* @return 成功返回链栈堆区首地址,失败返回NULL
*/
Stacklink CreateLink()
{
Stacklink top = (Stacklink)malloc(sizeof(struct Node));
if(top == NULL)
return NULL;
top->len = 0;
top->next = NULL;
return top;
}
/**
* @brief 压栈:头插
*
* @param top
* @param e 插入的元素
* @return int 成功返回0,失败返回-1
*/
int LinkStackPush(Stacklink top,datatype e)
{
if (top == NULL)
{
printf("\n链栈不存在,压栈失败!\n");
return -1;
}
//创建新结点
Stacklink p = (Stacklink)malloc(sizeof(struct Node));
if (p == NULL)
return -1;
p->data = e;
p->next = NULL;
//插入
p->next = top->next;
top->next = p;
top->len++;
return 0;
}
/**
* @brief 遍历输出链栈
*
* @param top
*/
void LinkStackShow(Stacklink top)
{
if (top == NULL || top->len == 0)
{
printf("\n数据元素不存在,遍历失败!\n");
return;
}
Stacklink p = top;
for (int i = 1; i <= top->len; i++)
{
p = p->next;
printf("%d",p->data);
}
printf("\n");
}
/**
* @brief 弹栈:头删
*
* @param top
* @return int 成功返回0,失败返回-1
*/
int LinkStackPop(Stacklink top)
{
int num;
if (top == NULL || top->len == 0)
{
printf("\n数据元素不存在,弹栈失败!\n");
return -1;
}
Stacklink p = top->next;
num = p->data;
top->next = p->next;
free(p);
p = NULL;
top->len--;
return num;
}
执行结果如下图所示:
![](https://img-blog.csdnimg.cn/5ceb399b5c8143dd9ebf0c0eb9f8dbf6.png)
![](https://img-blog.csdnimg.cn/c166afeff3db4dca85de76e1e2c66943.png)