-
Notifications
You must be signed in to change notification settings - Fork 27
/
chpt2-palindrome.js
107 lines (83 loc) · 2.39 KB
/
chpt2-palindrome.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
function isLinkedListPalindrome(headNode) {
// By definition, palindrome is same forward as backwards. One solution is to reverse the list and compare
var reversedNode = reverseLinkedList(headNode);
var regularNode = headNode;
while (reversedNode !== null || regularNode !== null) {
console.log(reversedNode.next, regularNode.next);
if (reversedNode.value !== regularNode.value) {
return false;
}
reversedNode = reversedNode.next;
regularNode = regularNode.next;
}
return true;
}
function reverseLinkedList(headNode) {
var currentNode = headNode;
var nextNode = null;
var previousNode = null;
while (currentNode) {
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
function LinkedList() {
this.head = null;
this.length = 0;
}
function Node(value) {
this.value = value;
this.next = null;
}
LinkedList.prototype.appendNode = function(value) {
var newNode = new Node(value);
var currentNode = this.head;
if (!currentNode) {
this.head = newNode;
this.length++;
return newNode;
}
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
this.length++;
return newNode;
};
LinkedList.prototype.printValues = function() {
var currentNode = this.head;
while (currentNode) {
currentNode = currentNode.next;
}
};
function isLinkedListPalindromeStack(headNode) {
// Another way to solve is to use a stack to store first half of linked list, then compare with second half
// How do we get 1st half without length? Can use runners
var stackOfValues = [];
var slowRunner = headNode;
var fastRunner = headNode;
// Advance the fast runner twice as fast, stop if we overshoot or if at end
while (fastRunner.next !== null && fastRunner !== null) {
stackOfValues.push(slowRunner.value);
slowRunner = slowRunner.next;
fastRunner = fastRunner.next.next;
}
// We have an odd number of nodes, so let's ignore the middle since it doesn't need to match
if (fastRunner !== null) {
slowRunner = slowRunner.next;
}
while (slowRunner !== null) {
if (slowRunner.value !== stackOfValues.pop()) {
return false;
}
slowRunner = slowRunner.next;
}
return true;
}
function Node(value) {
this.value = value;
this.next = null;
}