Anjan Dutta
Leet Code 876: Middle of the Linked List
Leet Code 876: Middle of the Linked List
Problem statement:
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Constraints:
- The number of nodes in the list is in the range [1, 100].
- 1 <= Node.val <= 100
Solution:
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @return {ListNode} */var middleNode = function(head) { let len = 1, index = 1; let temp = head; let arr = []; while(head.next!=null) { len++; head = head.next; } let mid = Math.ceil(len/2); if(len%2==0) { mid++; } while(mid>index) { temp = temp.next; index++; } return temp;};