-
Notifications
You must be signed in to change notification settings - Fork 7
/
solution.ts
56 lines (54 loc) · 1.6 KB
/
solution.ts
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
51
52
53
54
55
56
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Two_Pointers #Stack #Linked_List
// #Recursion #Level_2_Day_3_Linked_List #Udemy_Linked_List #Big_O_Time_O(n)_Space_O(1)
// #2023_10_09_Time_96_ms_(95.67%)_Space_72.8_MB_(87.01%)
/*
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function isPalindrome(head: ListNode | null): boolean {
if (head === null || head.next === null) {
// Empty list or single element is considered a palindrome.
return true
}
let len = 0
let right = head
// Calculate the length of the list.
while (right !== null) {
right = right.next
len++
}
// Find the middle of the list.
let middle = Math.floor(len / 2)
// Reset the right pointer to the head.
right = head
// Move the right pointer to the middle of the list.
for (let i = 0; i < middle; i++) {
right = right.next
}
// Reverse the right half of the list.
let prev = null
while (right !== null) {
const next = right.next
right.next = prev
prev = right
right = next
}
// Compare the left and right halves.
for (let i = 0; i < middle; i++) {
if (prev !== null && head.val === prev.val) {
head = head.next
prev = prev.next
} else {
return false
}
}
return true
}
export { isPalindrome }