Middle of the Linked List

Try to solve the Middle of the Linked List problem.

Statement#

Given the head of a singly linked list, return the middle node of the linked list. If the number of nodes in the linked list is even, there will be two middle nodes, so return the second one.

Constraints:

Let n be the number of nodes in a linked list.

  • 11 \leq n 100\leq 100
  • 11 \leq node.data 100\leq 100
  • head \neq NULL

Examples#

Created with Fabric.js 3.6.6 NULL 3 4 1 2 5 3 Sample example 1

1 of 3

Created with Fabric.js 3.6.6 NULL 4 5 1 2 3 6 4 Sample example 2

2 of 3

Created with Fabric.js 3.6.6 NULL 2 1 2 Sample example 3

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Middle of the Linked List

1

What is the output if the following linked list is given as input?

2 → 4 → 6 → 8 → 10 → NULL

A)

4

B)

6

C)

2

D)

8

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Create two pointers, slow and fast, initially at the head of the linked list.

Traverse the linked list while moving the slow pointer one step forward and the fast pointer two steps forward.

When the fast pointer reaches the last node or NULL, the slow pointer will point to the middle node of the linked list.

Return the node that the slow pointer points to.


Try it yourself#

Implement your solution in main.py in the following coding playground. We have provided a few useful code templates in the other files that you may build on to solve this problem.

Python
main.py
linked_list_node.py
linked_list.py
linked_list_reversal.py
linked_list_traversal.py
Input #1
%0 node_01 1 node_11 2 node_01->node_11 node_21 3 node_11->node_21 node_31 4 node_21->node_31 node_41 5 node_31->node_41
Visualization for Input #1
Middle of the Linked List

Solution: Linked List Cycle

Solution: Middle of the Linked List