-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome.js
80 lines (68 loc) · 1.39 KB
/
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
// Singly linked list
class LinkedList {
constructor() {
this.head = this.tail = null;
this.size = 0;
}
// add it to the end of list
append(value) {
const node = new Node(value);
if (!this.tail) {
this.tail = this.head = node;
} else {
let oldTail = this.tail;
this.tail = node;
oldTail.next = this.tail;
}
return node;
}
// add it to the start of list
prepend(value) {
const node = new Node(value);
if (!this.head) {
this.head = this.tail = node;
} else {
let oldHead = this.head;
this.head = node;
this.head.next = oldHead;
}
return node;
}
// Palidrom
isPalindrom() {
let curr = this.head;
let stack = new Set();
while (curr != null) {
if (stack.has(curr.data)) {
stack.delete(curr.data);
} else {
stack.add(curr.data);
}
curr = curr.next;
}
if (stack.size <= 1) {
return console.log("It is a plaindrome");
} else {
return console.log("It' not");
}
}
show() {
let curr = this.head;
while (curr.next != null) {
console.log(curr.data);
curr = curr.next;
}
}
}
class Node {
constructor(value, next) {
this.data = value;
this.next = next || null;
}
}
// Intializing Chars
let str = new LinkedList();
for (let char of "racecar") {
str.append(char);
}
str.isPalindrom();