È stato utile?

Domanda

Program to find the middle node of a singly linked list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a singly linked list node, we have to find the value of the middle node. And when there are two middle nodes, then we will return the second one. We have to try to solve this in single pass.

So, if the input is like [5,9,6,4,8,2,1,4,5,2], then the output will be 2.

To solve this, we will follow these steps−

  • p:= node

  • d:= 0, l:= 0

  • while node is not null, do

    • if d is not same as 2, then

      • node:= next of node

      • l := l + 1, d := d + 1

    • otherwise,

  • p:= next of p, d:= 0

    • return val of p when l is odd otherwise value of next of p

Let us see the following implementation to get better understanding

Example

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
   def make_list(elements):
      head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
         ptr.next = ListNode(element)
      return head
class Solution:
   def solve(self, node):
      p=node
      d=0
      l=0
   while node:
      if d!=2:
         node=node.next
         l+=1
         d+=1
      else:
         p=p.next
         d=0
   return p.val if l & 1 else p.next.val
ob = Solution()
head = make_list([5,9,6,4,8,2,1,4,5,2])
print(ob.solve(head))

Input

Input:
[5,9,6,4,8,2,1,4,5,2]

Output

2
raja
Published on 05-Oct-2020 16:12:49
Advertisements
È stato utile?
Non affiliato a Tutorialspoint
scroll top