C语言实现链表十进制转十六进制 子函数声明是typedef char datatype; typedef struct { datatype data[Size]; datatype top; }SeqStack;
时间: 2024-05-15 20:12:13 浏览: 102
下面是一个将链表中的十进制数转换为十六进制数的函数实现,其中用到了上述提供的SeqStack结构体实现栈:
```
#include <stdio.h>
#include <stdlib.h>
#define Size 100
typedef char datatype;
typedef struct node {
int data;
struct node *next;
} Node, *List;
typedef struct {
datatype data[Size];
datatype top;
} SeqStack;
void InitStack(SeqStack *S);
int StackEmpty(SeqStack S);
int StackFull(SeqStack S);
void Push(SeqStack *S, datatype x);
datatype Pop(SeqStack *S);
int GetTop(SeqStack S, datatype *x);
void Conversion(List L);
int main() {
// 构造链表
List L = (List)malloc(sizeof(Node));
List p = L;
int num;
printf("Please input decimal numbers, end with -1:\n");
scanf("%d", &num);
while (num != -1) {
p->data = num;
p->next = (List)malloc(sizeof(Node));
p = p->next;
scanf("%d", &num);
}
p->next = NULL;
// 转换为十六进制输出
printf("The hexadecimal numbers are:\n");
Conversion(L);
return 0;
}
void InitStack(SeqStack *S) {
S->top = -1;
}
int StackEmpty(SeqStack S) {
return S.top == -1;
}
int StackFull(SeqStack S) {
return S.top == Size - 1;
}
void Push(SeqStack *S, datatype x) {
if (StackFull(*S)) {
printf("Stack is full!\n");
return;
}
S->data[++S->top] = x;
}
datatype Pop(SeqStack *S) {
if (StackEmpty(*S)) {
printf("Stack is empty!\n");
return '\0';
}
return S->data[S->top--];
}
int GetTop(SeqStack S, datatype *x) {
if (StackEmpty(S)) {
printf("Stack is empty!\n");
return 0;
}
*x = S.data[S.top];
return 1;
}
void Conversion(List L) {
SeqStack S;
InitStack(&S);
List p = L;
int num, remainder;
datatype hex;
while (p != NULL) {
num = p->data;
while (num) {
remainder = num % 16;
switch (remainder) {
case 10:
hex = 'A';
break;
case 11:
hex = 'B';
break;
case 12:
hex = 'C';
break;
case 13:
hex = 'D';
break;
case 14:
hex = 'E';
break;
case 15:
hex = 'F';
break;
default:
hex = remainder + '0';
break;
}
Push(&S, hex);
num /= 16;
}
while (!StackEmpty(S)) {
printf("%c", Pop(&S));
}
printf(" ");
p = p->next;
}
printf("\n");
}
```
其中,Conversion函数实现了链表中十进制数转十六进制的功能,具体过程是将每个节点的data字段转换为十六进制数后压入栈中,最后弹出栈中所有元素得到该节点的十六进制数表示。整体思路较为简单,需要注意的是可以使用switch语句将十进制数转为十六进制字符,而不必手动处理,这样代码可读性更好。
阅读全文