Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python How do you find the middle element of a singly linked list in one pass?

# Python 3 program to find the middle of a  
# given linked list 
  
class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
      
class LinkedList:
  
    def __init__(self):
        self.head = None
  
    # create Node and and make linked list
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
          
    def printMiddle(self):
        temp = self.head 
        count = 0
          
        while self.head:
  
            # only update when count is odd
            if (count & 1): 
                temp = temp.next
            self.head = self.head.next
  
            # increment count in each iteration 
            count += 1 
          
        print(temp.data)     
          
# Driver code
llist = LinkedList() 
llist.push(1)
llist.push(20) 
llist.push(100) 
llist.push(15) 
llist.push(35)
llist.printMiddle()
# code has been contributed by - Yogesh Joshi
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #python #How #find #middle #element #singly #linked #list
ADD COMMENT
Topic
Name
9+8 =