Title: Merging two ordered linked lists


Merges two ordered lists into a new ordered list and returns. A new list is formed by concatenating all the nodes of a given two lists.Copy the code

Example:


Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4Copy the code

Think about:


This problem, since it is an ordered list, simply creates a new head node and iterates through the two lists, comparing the val of each node and pointing the head node to the node with the smaller VAL. Finally, when a linked list reaches the end, all the nodes after another linked list can be connected to the back.Copy the code

Implementation:


class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode r = head; while (l1 ! = null && l2 ! = null) { if (l1.val < l2.val) { head.next = l1; l1 = l1.next; } else { head.next = l2; l2 = l2.next; } head = head.next; } if (l1 == null) { head.next = l2; } else { head.next = l1; } return r.next; }}Copy the code