Merge Two Sorted Lists
2017-09-14 本文已影响0人
Wenyue_offer
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while(l1 != null && l2 != null)
{
if(l1.val < l2.val)
{
p.next = l1;
p = p.next;
l1 = l1.next;
}
else
{
p.next = l2;
p = p.next;
l2 = l2.next;
}
}
if(l1 != null) p.next = l1;
else p.next = l2;
return dummy.next;
}
}