Skip to content

Instantly share code, notes, and snippets.

@caglarorhan
Created October 17, 2017 04:07

Revisions

  1. caglarorhan created this gist Oct 17, 2017.
    89 changes: 89 additions & 0 deletions LinkedList.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,89 @@
    function LinkedList(){
    this.head=null;
    this.tail=null;
    }

    function Node(value,next,prev){
    this.value=value;
    this.next=next;
    this.prev=prev;
    }


    LinkedList.prototype.addToHead = function(value){
    var newNode = new Node(value, this.head, null);
    if(this.head) this.head.prev=newNode;
    else this.tail =newNode;
    this.head = newNode;

    }

    LinkedList.prototype.addToTail = function(value){
    var newNode = new Node(value, null, this.tail);
    if(this.tail) this.tail.next = newNode;
    else this.head = newNode;
    this.tail = newNode;
    }


    LinkedList.prototype.removeHead = function(){
    if(!this.head) return null;
    var val = this.head.value;
    this.head = this.head.next;
    if(this.head) this.head.prev = null;
    else this.tail = null;
    return val;
    }

    LinkedList.prototype.removeTail = function(){
    if(!this.trail) return null;
    var val = this.trail.value;
    this.tail =this.tail.prev;
    if(this.tail) this.tail.next =null;
    else this.head = null;
    return val;
    }

    LinkedList.prototype.search = function(searchValue){
    var currentNode = this.head;

    while(currentNode){
    if(currentNode.value=== searchValue){return currentNode.value;}
    currentNode = currentNode.next;
    }
    return null;
    }


    LinkedList.prototype.indexOf = function(value){
    var currentNode=this.head;
    var indexes = [];
    var indexNo=0;
    while(currentNode){
    if(currentNode.value===value){
    indexes.push(indexNo);
    }
    currentNode = currentNode.next;
    indexNo++;
    }

    return indexes;

    }




    var myLL = new LinkedList();

    myLL.addToHead(123);
    myLL.addToHead('Deneme');
    myLL.addToHead(567);
    myLL.addToHead(123);
    myLL.addToTail(345345);
    myLL.addToTail(433);
    myLL.addToTail('Deneme');
    myLL.addToTail(433);


    //console.log(myLL.indexOf(433));