1
1
package g0201_0300 .s0234_palindrome_linked_list
2
2
3
- // #Easy #Top_100_Liked_Questions #Top_Interview_Questions # Two_Pointers #Stack #Linked_List
4
- // #Recursion # Level_2_Day_3_Linked_List #Udemy_Linked_List #Big_O_Time_O(n)_Space_O(1)
5
- // #2023_11_07_Time_811_ms_(85.71%)_Space_67.7_MB_(78 .57%)
3
+ // #Easy #Top_100_Liked_Questions #Two_Pointers #Stack #Linked_List #Recursion
4
+ // #Level_2_Day_3_Linked_List #Udemy_Linked_List #Big_O_Time_O(n)_Space_O(1)
5
+ // #2024_06_02_Time_912_ms_(100.00%)_Space_72_MB_(48 .57%)
6
6
7
7
import com_github_leetcode .ListNode
8
8
@@ -15,40 +15,42 @@ import com_github_leetcode.ListNode
15
15
*/
16
16
object Solution {
17
17
def isPalindrome (head : ListNode ): Boolean = {
18
- var len = 0
19
- var right = head
20
-
21
- // Calculate the length
22
- while (right != null ) {
23
- right = right.next
24
- len += 1
18
+ if (head == null || head.next == null ) {
19
+ return true
25
20
}
26
-
27
- // Reverse the right half of the list
28
- len = len / 2
29
- right = head
30
- for (_ <- 0 until len) {
31
- right = right.next
21
+ def reverseList (node : ListNode ): ListNode = {
22
+ var prev : ListNode = null
23
+ var current : ListNode = node
24
+ while (current != null ) {
25
+ val nextNode = current.next
26
+ current.next = prev
27
+ prev = current
28
+ current = nextNode
29
+ }
30
+ prev
32
31
}
33
32
34
- var prev : ListNode = null
35
- while (right != null ) {
36
- val next = right.next
37
- right.next = prev
38
- prev = right
39
- right = next
33
+ def findMiddle (node : ListNode ): ListNode = {
34
+ var slow = node
35
+ var fast = node
36
+ while (fast != null && fast.next != null ) {
37
+ slow = slow.next
38
+ fast = fast.next.next
39
+ }
40
+ slow
40
41
}
41
- var head2 = head
42
- // Compare left half and right half
43
- for (_ <- 0 until len) {
44
- if (prev != null && head2.x == prev.x) {
45
- head2 = head2.next
46
- prev = prev.next
47
- } else {
42
+
43
+ val middle = findMiddle(head)
44
+ var secondHalf = reverseList(middle)
45
+
46
+ var firstHalf = head
47
+ while (secondHalf != null ) {
48
+ if (firstHalf.x != secondHalf.x) {
48
49
return false
49
50
}
51
+ firstHalf = firstHalf.next
52
+ secondHalf = secondHalf.next
50
53
}
51
-
52
54
true
53
55
}
54
56
}
0 commit comments