Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
mitcc committed Nov 27, 2013
1 parent fcac6d0 commit cb905c9
Showing 1 changed file with 33 additions and 44 deletions.
77 changes: 33 additions & 44 deletions leetcode/MergeTwoSortedLists.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,50 +13,39 @@
* }
* }
*/
package info.mitcc.leetcode;

public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
if(l2 == null)
return l1;
if(l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}

/* ListNode result;
if(l1.val < l2.val) {
result = l1;
result.next = mergeTwoLists(l1.next, l2);
} else {
result = l2;
result.next = mergeTwoLists(l1, l2.next);
}
return result;*/
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
else if(l2 == null)
return l1;
else if(l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}

/* public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode temp = result;
while(l1 != null & l2 != null) {
if(l1.val < l2.val) {
temp.next = l1;
l1 = l1.next;
} else {
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if(l1 != null)
temp.next = l1;
if(l2 != null)
temp.next = l2;
return result.next;
}*/
/*************************************************************/

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0), cur = res;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(l1 == null)
cur.next = l2;
else if(l2 == null)
cur.next = l1;
return res.next;
}
}

0 comments on commit cb905c9

Please sign in to comment.