Reputation: 69
The following code is supposed to take an integer (which is numerator) and convert it into a linked list, starting from the very end. As an example, for the integer 603, I want to create 3->0->6. But for some reason, my output only gives me 0->6, and completely ignores the 3? I've looked over my code and I just can't seem to see where my logic is going wrong.
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;
}
}
Upvotes: 0
Views: 168
Reputation: 136208
Your code loses the head of the list because it is stored in ptr
which is changed on each insertion.
You can append a node to a singly-linked list in a more efficient manner:
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;
Upvotes: 2