Data Structure In JavaScript – Find The Middle Element In Linked List

function LinkedList() {
  this.head = null;
}
function Node(data) {
  this.node = data;
  this.next = null 
}
LinkedList.prototype.add = function(data) {
  let mainHead = this.head;
  if(!mainHead) {
    this.head = new Node(data);
  } else {
    while(mainHead.next !== null ){
      mainHead = mainHead.next;
    }
    mainHead.next = new Node(data);
  }
  return this.head;
}
LinkedList.prototype.list = function() {
  let mainHead = this.head;
  while(mainHead.next !== null) {
    console.log(mainHead.node);
    mainHead = mainHead.next;
  }
  console.log(mainHead.node)
}

LinkedList.prototype.middleElement = function() {
  let mainHead = this.head;
  let singleIncremntCounter = mainHead;
  let doubleIncrementCounter = mainHead;

  while(doubleIncrementCounter.next !== null && doubleIncrementCounter.next.next !== null) {
    singleIncremntCounter = mainHead.next;
    doubleIncrementCounter = doubleIncrementCounter.next.next;
    mainHead = mainHead.next;
  }

  console.log(singleIncremntCounter.node);

}
let linkedList = new LinkedList();
linkedList.add(5);
linkedList.add(15);
linkedList.add(25);
linkedList.add(35);
linkedList.add(45);
linkedList.add(55);
linkedList.add(56);
linkedList.add(65);
linkedList.add(66);
linkedList.add(77);
linkedList.add(88);
linkedList.add(99);
linkedList.add(90);
linkedList.add(96);
linkedList.add(985);
linkedList.add(986);
linkedList.add(987);

Leave a Reply

Your email address will not be published. Required fields are marked *