Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

PREVIOUS NEXT
Code Example
Python :: python observer pattern 
Python :: python melt 
Python :: torch.nan_to_num 
Python :: pandas fill missing index values 
Python :: |= operator python 
Python :: how to use a class in python 
Python :: django upload multiple files 
Python :: python lambda function use global variable 
Python :: python looping over a list 
Python :: python catch int conversion error 
Python :: using hashlib module in python 
Python :: insert-cells-in-empty-pandas-dataframe 
Python :: shape 
Python :: how to check python to see if list length is even 
Python :: python any in string 
Python :: python conditionals 
Python :: how to address null in python 
Python :: python linter online 
Python :: plot histogram from counts and bin edges 
Python :: iterate last day of months python 
Python :: #index operator in python 
Python :: optional parameter in python 
Python :: dictionary increment 
Python :: Python script to SSH to server and run command 
Python :: pandas dataframe check for values more then a number 
Python :: puython is not equal to 
Python :: pandas read csv with lists 
Python :: using shebang python 
Python :: python how to exit function 
Python :: app.py 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =