Skip to content

Instantly share code, notes, and snippets.

@kalecser
Last active December 20, 2015 19:09
Show Gist options
  • Save kalecser/6180833 to your computer and use it in GitHub Desktop.
Save kalecser/6180833 to your computer and use it in GitHub Desktop.
IsPalindrome JavaScript SinglyLinkedList
Node = function(char){
this.char = char;
};
Node.prototype = {
createNext: function(char){
this.next = new Node(char);
return this.next;
}
}
var asLinkedList = function(subject){
var head = new Node(subject[0]);
var current = head;
var i = 1;
while(i < subject.length){
current = current.createNext(subject[i++]);
}
return head;
}
var reverseLink = function(node){
var previous = null;
while (true){
next = node.next;
node.next = previous;
if (!next) return node;
previous = node;
node = next;
}
}
var mid = function(head){
var mid = head;
var current = head;
var count = 0;
while(current.next != null && current.next.next != null){
count++;
current = current.next.next;
mid = mid.next;
}
if ((count % 2) == 0)
mid = mid.next;
return mid;
}
var isPalindrome = function(head) {
tail = reverseLink(mid(head))
while (tail.char == head.char){
if (tail.next == null|| head.next == null){
return true;
}
tail = tail.next;
head = head.next;
}
return tail;
}
console.debug(isPalindrome(asLinkedList("aaa")));
console.debug(isPalindrome(asLinkedList("abccba")));
console.debug(isPalindrome(asLinkedList("lonnol")));
console.debug(isPalindrome(asLinkedList("bob")));
console.debug(isPalindrome(asLinkedList("1001")));
console.debug(isPalindrome(asLinkedList("Igor")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment