Skip to content

Instantly share code, notes, and snippets.

@javi-aire
Created April 9, 2020 01:07
Show Gist options
  • Save javi-aire/03b288c2a898b52e8888e8d587bc9643 to your computer and use it in GitHub Desktop.
Save javi-aire/03b288c2a898b52e8888e8d587bc9643 to your computer and use it in GitHub Desktop.
Problem 8/30 of LeetCode 30-day challenge
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
let middleNode = function(head) {
let length = 1;
let currentNode = head;
// node to return
let targetNode;
while(currentNode.next !== null){
// counts the length of the linkedlist
length++;
currentNode = currentNode.next;
}
// case for just one node
if(length === 1){
return head;
}
/*
* if the length is even, add 1 to mid
* to handle case for two middle nodes
*/
let mid = length % 2 === 0 ? Math.ceil(length / 2) + 1 : Math.ceil(length / 2);
let i = 1;
let node = head;
// while loop, but make it for
while((node.next !== null) && i < length) {
node = node.next;
i++;
if(i === mid){
targetNode = node;
}
}
return targetNode;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment