-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 174 ms (33.57%), Space: 35.1 MB (76.40%) - LeetHub
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.kt
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,33 @@ | ||
/** | ||
* Example: | ||
* var li = ListNode(5) | ||
* var v = li.`val` | ||
* Definition for singly-linked list. | ||
* class ListNode(var `val`: Int) { | ||
* var next: ListNode? = null | ||
* } | ||
*/ | ||
class Solution { | ||
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { | ||
val head = ListNode() | ||
var tail = head | ||
|
||
var currentL1 = list1 | ||
var currentL2 = list2 | ||
|
||
while (currentL1 != null && currentL2 != null) { | ||
if (currentL1.`val` < currentL2.`val`) { | ||
tail.next = currentL1 | ||
currentL1 = currentL1.next | ||
} else { | ||
tail.next = currentL2 | ||
currentL2 = currentL2.next | ||
} | ||
tail = tail.next | ||
} | ||
|
||
tail.next = if (currentL1 == null) currentL2 else currentL1 | ||
|
||
return head.next | ||
} | ||
} |