forked from neetcode-gh/leetcode
-
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.
- Loading branch information
1 parent
d755dad
commit cff97dd
Showing
1 changed file
with
38 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,38 @@ | ||
/** | ||
* 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 reverseList(head: ListNode?): ListNode? { | ||
if (head == null) | ||
return head | ||
|
||
var prev: ListNode? = null | ||
var curr = head | ||
|
||
while (curr != null) { | ||
val next = curr.next | ||
curr.next = prev | ||
prev = curr | ||
curr = next | ||
} | ||
|
||
return prev | ||
} | ||
|
||
fun reverseListRecursive(head: ListNode?): ListNode? { | ||
if (head == null || head.next == null) | ||
return head | ||
|
||
val newHead = reverseList(head.next) | ||
head.next.next = head | ||
head.next = null | ||
|
||
return newHead | ||
} | ||
} |