-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234.js
120 lines (112 loc) · 2.04 KB
/
234.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
const isPalindrome = (head) => {
// v1
// let reversedList = null;
// let node = head;
// while (node !== null) {
// const newNode = {
// val: node.val,
// next: reversedList,
// };
// node = node.next;
// reversedList = newNode;
// }
// let i = head;
// let j = reversedList;
// while (i !== j) {
// if (i.val !== j.val) {
// return false;
// }
// i = i.next;
// j = j.next;
// }
// return true;
//v2
// let node = head;
// let prev = null;
// while (node !== null) {
// node.prev = prev;
// prev = node;
// node = node.next;
// }
// let i = head;
// let j = prev;
// while (i !== j) {
// if (i.val !== j.val) {
// return false;
// }
// i = i.next;
// j = j.prev;
// }
// return true;
// v3
// const result = [];
// let node = head;
// while (node !== null) {
// result.push(node.val);
// node = node.next;
// }
// let left = 0;
// let right = result.length - 1;
// while (left < right) {
// if (result[left] !== result[right]) {
// return false;
// }
// left += 1;
// right -= 1;
// }
// return true;
// v4
let slow = head;
let fast = head;
while (fast && fast.next) {
fast = fast.next.next;
slow = slow.next;
}
let last = null;
while (slow !== null) {
let temp = slow.next;
slow.next = last;
last = slow;
slow = temp;
}
let i = head;
let j = last;
while (j) {
if (i.val !== j.val) {
return false;
}
i = i.next;
j = j.next;
}
return true;
};
isPalindrome({
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 3,
next: {
val: 2,
next: {
val: 1,
next: null,
},
},
},
},
},
});