Instagram
youtube
Facebook
Twitter

Middle of the Linked List Leetcode Solution

In this tutorial, we are going to solve a leetcode problem, Middle of the linked list in python.

Task:

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.

 

Example1:

Example2:

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

 

Solution:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        lst = []
        curr = head
        while curr != None:
            lst.append(curr.val)
            curr = curr.next
        n = len(lst)
        
        lst = lst[n//2 : ]
        return self.ll(lst)
        
            
    def ll(self, lst):
        head = ListNode(lst[0])
        cur = head
        for i in range(1, len(lst)):
            cur.next = ListNode(lst[i])
            cur = cur.next
        return head
        

Steps:

step1: The Approach to this problem is broken down into three steps. The first one is to store the value of the nodes into a list then, and the second step is to modify that list to store its elements from the middle of the list till the end, and then again made the modified list a linked list and return its head.

step2: create an empty list and go through the entire linked list and append the value of the node into the list.

step3: Now, create another function named ll which then returns the linked list from the list.

step4: Now call the ll function on lst but after applying list comprehension.

step5: Now the ll function will return the linked list whose head is the middle element of the lst.