Merge Two Sorted Lists 解答

时间:2021-05-13 09:10:03

Question

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Solution

The key to the solution here is to create a new linked list by creating a fake head.

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l2 == null)
return l1;
if (l1 == null)
return l2;
ListNode fakeHead = new ListNode(0);
ListNode tmp = fakeHead;
ListNode p1 = l1, p2 = l2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
tmp.next = p1;
p1 = p1.next;
} else {
tmp.next = p2;
p2 = p2.next; }
tmp = tmp.next;
}
while (p1 != null) {
tmp.next = p1;
tmp = tmp.next;
p1 = p1.next;
}
while (p2 != null) {
tmp.next = p2;
tmp = tmp.next;
p2 = p2.next;
}
return fakeHead.next;
}
}