Find max element of linked list in python
Python program for Find max element of linked list. Here problem description and other solutions.
# Python 3 program for
# Find largest element in linked list
# Linked list node
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
class SingleLL :
def __init__(self) :
self.head = None
self.tail = None
def insert(self, data) :
node = LinkNode(data)
if (self.head == None) :
# Add first node
self.head = node
else :
# Add node at the end position
self.tail.next = node
# New last node
self.tail = node
# Display linked list element
def display(self) :
if (self.head == None) :
return
temp = self.head
# iterating linked list elements
while (temp != None) :
print("", temp.data , end = " →")
# Visit to next node
temp = temp.next
print(" NULL")
# Find largest node in linked list
def findLargest(self) :
if (self.head == None) :
print("\n Empty linked list")
return
# Display linked list
self.display()
# Define some auxiliary variables
result = self.head
temp = self.head.next
# iterating linked list elements
while (temp != None) :
if (result.data < temp.data) :
# Get a new big node
result = temp
# Visit to next node
temp = temp.next
print(" Largest Element : ", result.data)
def main() :
list1 = SingleLL()
list2 = SingleLL()
list3 = SingleLL()
# Add node in first linked list
# 6 → 4 → 5 → 10 → 3 → 17 → 9 → 2 → 8 → NULL
list1.insert(6)
list1.insert(4)
list1.insert(5)
list1.insert(10)
list1.insert(3)
list1.insert(17)
list1.insert(9)
list1.insert(2)
list1.insert(8)
# Add node in second linked list
# 4 → 12 → 3 → 5 → 1 → 4 → NULL
list2.insert(4)
list2.insert(12)
list2.insert(3)
list2.insert(5)
list2.insert(1)
list2.insert(4)
# Add node in third linked list
# 2 → -9 → 8 → 4 → 8 → -7 → 9 → 2 → NULL
list3.insert(2)
list3.insert(-9)
list3.insert(8)
list3.insert(4)
list3.insert(8)
list3.insert(-7)
list3.insert(9)
list3.insert(2)
# Test
list1.findLargest()
list2.findLargest()
list3.findLargest()
if __name__ == "__main__": main()
Output
6 → 4 → 5 → 10 → 3 → 17 → 9 → 2 → 8 → NULL
Largest Element : 17
4 → 12 → 3 → 5 → 1 → 4 → NULL
Largest Element : 12
2 → -9 → 8 → 4 → 8 → -7 → 9 → 2 → NULL
Largest Element : 9
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment