Algorithm
Problem Name: 876. Middle of the Linked List
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.
Example 1:
Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
ListNode* middleNode(ListNode* head) {
auto a = head, b = head;
while(b && b->next) a = a->next, b = b->next->next;
return a;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const middleNode = function (head) {
if (head == null) return null
let count = 1
let iter = head
while (iter.next) {
iter = iter.next
count++
}
count = (count / 2) >> 0
while (count) {
head = head.next
count--
}
return head
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
class Solution:
def middleNode(self, head):
root, n = head, 0
while head:
head = head.next
n += 1
for _ in range(n // 2):
root = root.next
return root
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0876_MiddleOfTheLinkedList
{
public ListNode MiddleNode(ListNode head)
{
var fast = head;
var slow = head;
while (fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output