slow and fast pointer

by Krishna Ananthi

JavaScript

function Node(val, next){
	this.val = (val === undefined) ? 0: val;
  this.next = (next === undefined) ? null:next;
}

function middleNode(head){
		let slow = head, fast = head;
    while(fast && fast.next){
    	slow = slow.next;
      fast = fast.next.next;
    }
	return slow;
}

const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
const n4 = new Node(4);

n1.next = n2;
n2.next = n3;
n3.next = n4;

const res = middleNode(n1);
console.log(res.val);