-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-unsafe.ts
77 lines (63 loc) · 1.38 KB
/
solution-unsafe.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @lc app=leetcode id=234 lang=javascript
*
* [234] Palindrome Linked List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
type MaybeList = ListNode | null;
interface ListNode {
val: number;
next: MaybeList;
}
/**
* @param {ListNode} head
* @return {boolean}
*/
const isPalindrome = (head: MaybeList): boolean => {
// * ['56 ms', '94.77 %', '39.1 MB', '100 %']
if (head === null || head.next === null) return true;
// * find half node
let fast = head;
let slow = head;
while (fast.next && fast.next.next) {
slow = slow.next!;
fast = fast.next.next;
}
// * reverse second half part of list
let p1: MaybeList = head;
let p2: MaybeList = reverseList(slow.next!);
// // * mark for restore data mutation
// const halfDummy = slow;
// const halfHead = p2;
// * checking
while (p2 && p1) {
if (p1.val !== p2.val) return false;
p1 = p1.next;
p2 = p2.next;
}
// // * restore our mutation
// halfDummy.next = reverseList(halfHead);
return true;
};
const reverseList = (head: MaybeList): MaybeList => {
// * leetcode 206
let cur = head;
let prev = null;
let next;
while (cur !== null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
};
// @lc code=end
export { isPalindrome };