Merge Two Sorted Lists
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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(l1==null && l2==null) {
return null;
} else if (l1==null && l2!=null) {
return l2;
} else if (l1!=null && l2==null) {
return l1;
} else {
ListNode head = null;
ListNode p1 = null;
ListNode p2 = null;
if(l1.val<l2.val) {
head = l1;
p1 = head.next;
p2 = l2;
} else {
head = l2;
p1 = l1;
p2 = head.next;
}
ListNode cur = head;
while(p1!=null || p2!=null) {
if(p1==null || (p2!=null && p2.val<p1.val)) {
cur.next = p2;
cur = p2;
p2 = p2.next;
} else if(p2==null || (p1!=null && p1.val<=p2.val)) {
cur.next = p1;
cur = p1;
p1 = p1.next;
}
}
return head;
}
}
}
没有评论:
发表评论