forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0234-palindrome-linked-list.kt
42 lines (37 loc) · 1022 Bytes
/
0234-palindrome-linked-list.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
}
}