努力将整数转换为链表。不知道我在这里做错了什么

Struggling to convert an integer into a linked list. Not sure what I'm doing wrong here

本文关键字:在这里 错了 什么 不知道 整数 转换 链表 努力      更新时间:2023-10-16

下面的代码应该取一个整数(它是分子(,并从最后开始将其转换为链表。例如,对于整数603,我想创建3->0->6。但由于某种原因,我的输出只给了我0->6,而完全忽略了3?我查看了我的代码,但似乎看不出我的逻辑哪里出了问题。

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
}
int numerator = sum1 + sum2;
ListNode * ptr;
while (numerator != 0) {
int val = numerator % 10;
numerator = numerator / 10;
ListNode * node = new ListNode(val);
// If list is empty, add node.
if (!ptr) {
ptr = node;
// If list is not empty, traverse to end of list and then append.
} else {
while (ptr->next) {
ptr = ptr->next;
}
ptr->next = node;
}
}

您的代码会丢失列表的头部,因为它存储在每次插入时都会更改的ptr中。

你可以用一种更有效的方式将一个节点附加到单链表中:

ListNode* head = 0;
ListNode** tail = &head;
// ...    
// Append the new node to the tail of the list.
ListNode* node = new ListNode(val);
*tail = node;
tail = &node->next;
相关文章: