is Palindrome via LinkedList - Node.js Data Structure

Node.js examples for Data Structure:List

Description

is Palindrome via LinkedList

Demo Code


function Node(value){
    this.value = value;//  w w w  .  j a v  a 2s .c om
    this.next = null;
}
function SLL(){
    this.head = null;
    this.length = 0;
}
SLL.prototype.add = function(value){
    var node = new Node(value)
    var currentNode = this.head;
    if(!currentNode){
        this.head = node;
        this.length++;
        return node;
    }
    while(currentNode.next){
        currentNode = currentNode.next;
    }
    currentNode.next = node;
    this.length++;
    return node;
}

function isPalindrome (sll){
    var current = sll.head
    var middle = findMiddle(current)
    var rNode = reverseNode(middle)
    while(rNode !== null){
        if(current.value !== rNode.value){
            return false;
        }
        current = current.next;
        rNode = rNode.next;
    }
    return true;

    function findMiddle(node){
        var fast = node;
        var slow = node;
        while(slow && fast && fast.next){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    function reverseNode(node){
        if(node === null || node.next === null){
            return node
        }
        var prev = null;
        var curr = node;
        while( curr !== null){
            var temp = curr;
            curr = curr.next;
            temp.next = prev;
            prev = temp;
        }
        return prev;
    }
}

var sll = new SLL()
sll.add(1)
sll.add(2)
sll.add(3)
sll.add(3)
sll.add(2)
sll.add(1)

console.log(isPalindrome(sll))

Related Tutorials