Skip to content

Commit 8f4638b

Browse files
committed
Create 0234-palindrome-linked-list.kt
1 parent 7977007 commit 8f4638b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

kotlin/0234-palindrome-linked-list.kt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Example:
3+
* var li = ListNode(5)
4+
* var v = li.`val`
5+
* Definition for singly-linked list.
6+
* class ListNode(var `val`: Int) {
7+
* var next: ListNode? = null
8+
* }
9+
*/
10+
class Solution {
11+
fun isPalindrome(head: ListNode?): Boolean {
12+
13+
var slow = head
14+
var fast = head
15+
16+
// find the middle
17+
while(fast != null && fast.next != null) {
18+
fast = fast?.next?.next
19+
slow = slow?.next
20+
}
21+
22+
//reverse the right part of list (from middle to end)
23+
var prev: ListNode? = null
24+
while(slow != null) {
25+
val temp = slow?.next
26+
slow?.next = prev
27+
prev = slow
28+
slow = temp
29+
}
30+
31+
//traverse both divided parts, left and right portion, to check if palindrome
32+
var left = head
33+
var right = prev
34+
while(right != null) {
35+
if(right?.`val` != left?.`val`) return false
36+
left = left?.next
37+
right = right?.next
38+
}
39+
40+
return true
41+
}
42+
}

0 commit comments

Comments
 (0)