-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeLinkedList.kt
50 lines (42 loc) · 1.17 KB
/
PalindromeLinkedList.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
43
44
45
46
47
48
49
50
package problems
import problems.datastructure.ListNode
import java.lang.StringBuilder
class PalindromeLinkedList {
//
/**
* Could you do it in O(n) time and O(1) space? <-- No Stack
*
* Space O(1) - Must Reverse; Cannot Convert it to Int and compare;
* Space O(n) - Stack
*
* Int is faster than String.
* But Int wont work because "The number of nodes in the list is in the range [1, 105]"
*
* So... by the time **fast** reaches zero, **slow** will be at half.
*/
fun isPalindrome(head: ListNode?): Boolean {
var slow = head
var fast = head
while (fast?.next != null) {
fast = fast.next?.next
slow = slow?.next
}
var prev: ListNode? = null
while (slow != null) {
val temp = slow.next
slow.next = prev
prev = slow
slow = temp
}
var left = head
var right = prev
while (right != null) {
if (left?.`val` != right.`val`) {
return false
}
left = left.next
right = right.next
}
return true
}
}