Skip to content

Instantly share code, notes, and snippets.

@mohitmakhija1
Last active March 28, 2017 20:00
Show Gist options
  • Save mohitmakhija1/7e0cb159fdb91b876eb1fdbf71e9ed34 to your computer and use it in GitHub Desktop.
Save mohitmakhija1/7e0cb159fdb91b876eb1fdbf71e9ed34 to your computer and use it in GitHub Desktop.
Code to find the middle node in the linked list in single traversal in python.
# program to find the middle node of the Linked List in single traversal
class LinkedList:
def __init__(self):
self.head = None
# returns true is LinkedList is Empty
def isEmpty(self):
if self.head is None:
return True
else:
return False
# method adds elements to the left of the Linked List
def addToStart(self, data):
# create a temporary node
tempNode = Node(data)
tempNode.setLink(self.head)
self.head = tempNode
del tempNode
# method adds elements to the right of the Linked List
def addToEnd(self, data):
start = self.head
tempNode = Node(data)
while start.getNextNode():
start = start.getNextNode()
start.setLink(tempNode)
del tempNode
return True
# method displays Linked List
def display(self):
start = self.head
if start is None:
print("Empty List!!!")
return False
while start:
print(str(start.getData()), end=" ")
start = start.link
if start:
print("-->", end=" ")
print()
# method that returns the middle node of the list
def middleNode(self):
start = self.head
slow = self.head
fast = self.head
while True:
if fast.getNextNode():
fast = fast.getNextNode()
slow = slow.getNextNode()
else:
break
if fast.getNextNode():
fast = fast.getNextNode()
else:
break
return slow.getData()
# node class
class Node:
# default value of data and link is none if no data is passed
def __init__(self, data=None, link=None):
self.data = data
self.link = link
# method to update the data feild of Node
def updateData(self, data):
self.data = data
# method to set Link feild the Node
def setLink(self, node):
self.link = node
# method returns data feild of the Node
def getData(self):
return self.data
# method returns address of the next Node
def getNextNode(self):
return self.link
# main method
# creating LinkedList
myList = LinkedList()
# adding some elements to the start of LinkedList
myList.addToStart(23)
myList.addToStart(1)
myList.addToStart(5)
myList.addToStart(26)
myList.addToStart(27)
myList.addToStart(28)
# adding some elements to the End of the LinkedList
myList.addToEnd(24)
myList.addToEnd(22)
myList.addToEnd(13)
print("The Elements of the Linked List are : ")
myList.display()
print("\nThe middle Element of the Linked List is : " + str(myList.middleNode()))
'''
The Elements of the Linked List are :
28 --> 27 --> 26 --> 5 --> 1 --> 23 --> 24 --> 22 --> 13
The middle Element of the Linked List is : 1
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment