File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments