Skip to content

Commit ff6f965

Browse files
author
Tony K Tan
committed
(attempt) 2.6
1 parent 1412cbd commit ff6f965

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
var LinkedList = require('./../util/LinkedList');
2+
3+
var palindrome = function(head) {
4+
var mid = head;
5+
var end = head;
6+
var isEven = true;
7+
var firstHalf = null;
8+
var frontNode = null;
9+
10+
while (end.next !== null) {
11+
isEven = true;
12+
if (firstHalf === null) {
13+
firstHalf = new LinkedList(mid.value);
14+
} else {
15+
frontNode = firstHalf;
16+
firstHalf = new LinkedList(mid.value);
17+
firstHalf.next = frontNode;
18+
}
19+
mid = mid.next;
20+
end = end.next;
21+
if (end.next !== null) {
22+
end = end.next;
23+
isEven = false;
24+
}
25+
}
26+
27+
if (!isEven) {
28+
mid = mid.next;
29+
}
30+
31+
while(mid !== null) {
32+
// console.log(mid.value, firstHalf.value);
33+
if (mid.value !== firstHalf.value) {
34+
return false;
35+
}
36+
mid = mid.next;
37+
if (firstHalf!== null) {
38+
firstHalf = firstHalf.next;
39+
}
40+
}
41+
return true;
42+
43+
};
44+
45+
var a = new LinkedList('a');
46+
var b = new LinkedList('b');
47+
var c = new LinkedList('c');
48+
var d = new LinkedList('d');
49+
var e = new LinkedList('c');
50+
var f = new LinkedList('b');
51+
var g = new LinkedList('a');
52+
53+
a.next = b;
54+
b.next = c;
55+
c.next = d;
56+
d.next = e;
57+
e.next = f;
58+
f.next = g;
59+
60+
console.log(palindrome(a));

0 commit comments

Comments
 (0)