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.
Create 0234-palindrome-linked-list.kt
- Loading branch information
Showing
1 changed file
with
42 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,42 @@ | ||
/** | ||
* 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 isPalindrome(head: ListNode?): Boolean { | ||
|
||
var slow = head | ||
var fast = head | ||
|
||
// find the middle | ||
while(fast != null && fast.next != null) { | ||
fast = fast?.next?.next | ||
slow = slow?.next | ||
} | ||
|
||
//reverse the right part of list (from middle to end) | ||
var prev: ListNode? = null | ||
while(slow != null) { | ||
val temp = slow?.next | ||
slow?.next = prev | ||
prev = slow | ||
slow = temp | ||
} | ||
|
||
//traverse both divided parts, left and right portion, to check if palindrome | ||
var left = head | ||
var right = prev | ||
while(right != null) { | ||
if(right?.`val` != left?.`val`) return false | ||
left = left?.next | ||
right = right?.next | ||
} | ||
|
||
return true | ||
} | ||
} |