-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #95 from kajurampatell/patch-4
Merge Two Sorted Lists
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* int val; | ||
* ListNode next; | ||
* ListNode() {} | ||
* ListNode(int val) { this.val = val; } | ||
* ListNode(int val, ListNode next) { this.val = val; this.next = next; } | ||
* } | ||
*/ | ||
class Solution { | ||
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { | ||
|
||
ListNode dummyNode = new ListNode(0); | ||
ListNode tail = dummyNode; | ||
while(true) | ||
{ | ||
if(list1 == null) | ||
{ | ||
tail.next = list2; | ||
break; | ||
} | ||
if(list2 == null) | ||
{ | ||
tail.next = list1; | ||
break; | ||
} | ||
|
||
if(list1.val <= list2.val) | ||
{ | ||
tail.next = list1; | ||
list1 = list1.next; | ||
} | ||
else | ||
{ | ||
tail.next = list2; | ||
list2 = list2.next; | ||
} | ||
tail = tail.next; | ||
} | ||
return dummyNode.next; | ||
|
||
} | ||
} |