努力将整数转换为链表。不知道我在这里做错了什么
Struggling to convert an integer into a linked list. Not sure what I'm doing wrong here
下面的代码应该取一个整数(它是分子(,并从最后开始将其转换为链表。例如,对于整数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;
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- istringstream,num1 和 num2 在这里发生了什么?
- 我做错了什么?C++新手在这里
- R 值似乎为未命名的临时提供不完整的支持,还是我在这里遗漏了一些东西?
- 如果这不是 boost::lockfree::d etail::freelist 中的错误,我在这里错过了什么
- 此代码的输出是什么?我在这里错过了什么吗?
- 这个指针增量操作在这里实现了什么
- 我在这里滥用了模板吗?
- 尝试使用C++实现检测字符串中回文的递归版本.在这里遇到了一些麻烦
- AFAIK,下面的代码不应该编译,但它可以在 clang 和 GCC 中编译。我在这里错过了什么?
- 为什么 itr = vector.erase(itr) 在循环中导致内存库中断?我在这里做错了什么吗?
- 我在这里滥用了指针吗?虽然循环条件似乎无法正常工作
- 试图创建HIMAGELIST,我在这里做错了什么
- C ++中的构建错误,未定义的符号,在这里尝试了其他答案,无法弄清楚
- oStream&没有命名类型错误。我在这里做错了什么?
- {错误 C2338: (boost::has_trivial_destructor:<T>:value)} 对于 boost::lockfree::queue 是什么意思?我在这里错过了什
- 我的ArrayStack在这里发生了什么
- 为什么C/C++预处理器在这里添加了一个空格