https://leetcode.com/problems/merge-two-sorted-lists/

Recursive

Iterative

  • new node pointer is needed;
  • We need a loop for (list1 && list2), and conditions for when list1’s value is larger than list2’s value, and vice versa
  • After exiting the loop, check which list pointer is still valid, then simply append walker->next to that list pointer
  • Remember to assign walker to head, then delete the head

Mistakes

ListNode *head = new ListNode(); 
ListNode *walker = head; 
walker = list1; 
return head;
  • walker is first assigned to the newly allocated ListNode object. However it is then assigned to list1; now there is nobody connected to head!
  • Instead, do walker->next=list1 or head->next = walker