Skip to content

Commit 8a08096

Browse files
authored
Imprived task 234
1 parent 0bb8f80 commit 8a08096

File tree

1 file changed

+32
-30
lines changed

1 file changed

+32
-30
lines changed
Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package g0201_0300.s0234_palindrome_linked_list
22

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%)
66

77
import com_github_leetcode.ListNode
88

@@ -15,40 +15,42 @@ import com_github_leetcode.ListNode
1515
*/
1616
object Solution {
1717
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
2520
}
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
3231
}
3332

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
4041
}
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) {
4849
return false
4950
}
51+
firstHalf = firstHalf.next
52+
secondHalf = secondHalf.next
5053
}
51-
5254
true
5355
}
5456
}

0 commit comments

Comments
 (0)