Saturday, March 27, 2021

simple linked list with traversal forward and back ward

 The bare simple sample code shows how a simple linked list works. It also traverse the linked list.

both forward and backward.  I


class linkedList {
   no: number;
   next: linkedList;
   previous : linkedList;
}
  

  




class consumer {
  head = new linkedList();
  tail = new linkedList();
  createLinkedList() {
    //initialize head
    this.head.no = 1;
    var previous = this.head;
    var current = new linkedList();
    for (var i = 3; i <= 10; i++) {
       current = new linkedList();
      current.no = i;
      previous.next = current;
      current.previous = previous;
     
      previous = current;
      
    }
    //this.head.previous = current;
    this.tail = current;
    current =  this.head;
    while(current.next != null)
    {
      console.log(current.no)
      current = current.next;
    }
    console.log(current.no)
    while(this.tail.previous != null)
    {
      console.log(this.tail.previous.no);
      this.tail = this.tail.previous;
    }

    
  }
}
var consume = new consumer();
consume.createLinkedList();

type List = {
  no: number;
  next: linkedList;
}


No comments:

Post a Comment