Reputation: 1130
I have below program to define a Linked list:
class Node:
def __init__(self, data):
self.data = data
self.nxt = None
class lnklst:
def __init__(self):
self.start = None
def addNode(self,value):
nuNde = Node(value)
if self.start is None:
self.start = nuNde
else:
p = self.start
while p.nxt != None:
p = p.nxt
p.nxt = nuNde
def viewNde(self):
tp = self.start
while tp is not None:
print(tp.data, end=' <--> ')
tp = tp.nxt
def highEle(self):
a = self.start
b = a.nxt
while a:
if a.data > b.data:
a.data = b.data
tmp = a.data
a.data = self.start
self.start = tmp
I am able to create linked list, and view the elements. However, the logic to find the largest element(def highEle
) from the linked list is not working.
The logic to find the largest element as below:
- Take 2 pointers 'a' and 'b'.
- a = b
- Since, a = b, then b holds a.next
- Run a while loop until a is not None.
- Inside while loop, define a 'if' statement to check if `a.data > b.data`, then swap.
But the logic doesn't seems to be working. Please suggest.
Upvotes: 0
Views: 150
Reputation: 54867
This will return the largest number in the list.
def highEle(self):
sofar = 0
a = self.start
while a:
if a.data > sofar:
sofar = a.data
a = a.next
return sofar
Upvotes: 1