将链表转换为反转整数——C语言实现
链表转反转整数实现方案
需求说明
给定存储单个数字的链表,将其反转顺序后组成整数输出:
- 示例1:链表
3->4->2→ 输出243 - 示例2:链表
5->6->4→ 输出465
完整实现代码
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int val; struct Node *next; }node; // 统计链表节点数量 int getCount(node* head){ int count = 0; node* current = head; while(current != NULL){ count++; current = current->next; } return count; } // 计算反转后的整数 int getNumber(node* ptr,int size){ int result = 0; node* current = ptr; int power = size - 1; while(current != NULL){ // 用循环计算10的幂次,避免浮点精度问题 int ten_power = 1; for(int i = 0; i < power; i++){ ten_power *= 10; } result += current->val * ten_power; power--; current = current->next; } return result; } int main(){ struct Node * head; struct Node * second; struct Node * third; head = (node*) malloc(sizeof(node)); second = (node*) malloc(sizeof(node)); third = (node*) malloc(sizeof(node)); head->val = 2; head->next = second; second->val = 4; second->next = third; third->val = 6; third->next = NULL; // 动态获取链表长度,适配任意长度链表 int list_size = getCount(head); printf("%d", getNumber(head, list_size)); // 释放内存,避免泄漏 free(third); free(second); free(head); return 0; }
代码说明
- getCount函数:遍历链表统计节点总数,为后续幂次计算提供基础。
- getNumber函数:
- 遍历每个节点,将节点值与对应位的10的幂次相乘(如链表第一个节点对应反转后的个位,乘以10^0)
- 用循环实现幂次计算,规避
pow函数的浮点精度误差 - 累加所有节点的计算结果,得到最终反转整数
- main函数优化:
- 不再硬编码链表长度,通过
getCount动态获取,支持任意长度链表 - 添加内存释放逻辑,避免内存泄漏
- 不再硬编码链表长度,通过
内容的提问来源于stack exchange,提问作者Shresth Gour
相关产品推荐
相关产品推荐

