Skip to content

Commit

Permalink
Leetcode 21 Merge Two Sorted Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
jiajionline committed Jul 1, 2023
1 parent f46985d commit 0ec8623
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 29 deletions.
29 changes: 23 additions & 6 deletions 0021_Merge Two Sorted Lists/MergeTwoSortedLists.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@ class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
if(list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}else{
list2.next = mergeTwoLists(list1, list2.next);
return list2;

ListNode preHead = new ListNode();
ListNode curr = preHead;

ListNode p1 = list1;
ListNode p2 = list2;

while(p1!=null && p2!=null)
{
if(p1.val <= p2.val){
curr.next = p1;
p1 = p1.next;
}else{
curr.next = p2;
p2 = p2.next;
}

curr = curr.next;
}

if(p1!=null) curr.next = p1;
if(p2!=null) curr.next = p2;

return preHead.next;
}
}
29 changes: 6 additions & 23 deletions 0021_Merge Two Sorted Lists/MergeTwoSortedLists_Recursion.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,12 @@ class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;

ListNode preHead = new ListNode();
ListNode curr = preHead;

ListNode p1 = list1;
ListNode p2 = list2;

while(p1!=null && p2!=null)
{
if(p1.val <= p2.val){
curr.next = p1;
p1 = p1.next;
}else{
curr.next = p2;
p2 = p2.next;
}

curr = curr.next;
if(list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}else{
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}

if(p1!=null) curr.next = p1;
if(p2!=null) curr.next = p2;

return preHead.next;
}
}

0 comments on commit 0ec8623

Please sign in to comment.