traversing in linked list - python

I was writing the code for traversing through the linked list but not getting the desired output.
The code is provided let me know the problem
class Node :
def __init__(self,data):
self.data = data
self.next = None
class Linklist :
def __init__(self):
self.head = None
def insert(self,newNode):
if self.head is None:
self.head = newNode
else:
lastNode = self.head
while True:
if lastNode is None:
break
lastNode = lastNode.next
lastNode.next = newNode
def printlinklist(self):
if self.head is None:
print("list is empty")
return
currentNode = self.head
while True:
if currentNode is None:
break
print(currentNode.data)
currentNode = currentNode.next
linklist = Linklist()
firstNode = Node("Aradhya")
linklist.insert(firstNode)
secondNode = Node("Sheila")
linklist.insert(secondNode)
thirdNode = Node("Diya")
linklist.insert(thirdNode)
linklist.printlinklist()

You're almost there!! You need to do this simple modification in the insert() method:
def insert(self,newNode):
if self.head is None:
self.head = newNode
else:
lastNode = self.head
while lastNode.next: #<-- change this instead of `while True`
#if lastNode is None: #<--- there is no point for this line
# break #<--- there is no point for this line#
lastNode = lastNode.next
lastNode.next = newNode

Related

Why I'm getting this error "AttributeError: 'linkList' object has no attribute 'data'" Merge Sorted link list python

Why I am getting this error? I have written all corrected but still not resolved.
Reversing the link list with optimal solution. Python programming
File "d:\DSA_Parctice\3_MonthsDSA\LinkList\ReverseLinkList.py", line 74, in
mergeTwoSortedLinkListOptimize
if list2.data <= list1.data:
AttributeError: 'linkList' object has no attribute 'data'
class Node:
def __init__(self,data):
self.data=data
self.next=None
class linkList:
def __init__(self):
self.Head=None
def insertAtBeg(self,data):
newNode = Node(data)
if self.Head == None:
self.Head = newNode
return
temp=self.Head
self.Head=newNode
self.Head.next=temp
def reverseLinkList(self):
preNode=None
currHead=self.Head
nextNode=self.Head
while currHead!=None:
nextNode=currHead.next
currHead.next=preNode
preNode=currHead
currHead=nextNode
self.Head=preNode
def printLinkList(self):
if self.Head==None:
print("Link List is Empty")
else:
temp=self.Head
while temp!=None:
print(temp.data, end=" ")
temp=temp.next
def mergeTwoSortedLinkListOptimize(list1,list2):
mergeList=Node(0)
mergeList.next = list1
while True:
if list1 is None:
list1 = list2
break
if list2 is None:
break
if list2.data <= list1.data:
temp = list1
list1= list2
list2 = list2.next
list1.next= temp
else: list1= list1.next
return mergeList.next
llist1=linkList()
llist1.insertAtBeg(3)
llist1.insertAtBeg(5)
llist1.insertAtBeg(6)
llist1.insertAtBeg(8)
llist1.insertAtBeg(9)
llist1.insertAtBeg(10)
llist2 = linkList()
llist2.insertAtBeg(1)
llist2.insertAtBeg(6)
llist2.insertAtBeg(7)
llist2.insertAtBeg(15)
llist1.reverseLinkList()
llist2.reverseLinkList()
llist1.printLinkList()
print()
llist2.printLinkList()
llist1=llist1.mergeTwoSortedLinkListOptimize(llist2)
llist1.printLinkList()
# I tried also like this "if temp1[0].data <= temp2[0].data:" but not resolved
# Why I am getting this error i have written all corrected but still not resolved.
File "d:DSA\LinkList\ReverseLinkList.py", line 74, in mergeTwoSortedLinkListOptimize
if list2.data <= list1.data:
AttributeError: 'linkList' object has no attribute 'data'
Please help me I am trying from two days
You are approaching this wrong.
mergeList=Node(0) this doesn't make sense. This should be an instance of linkList and not a standalone Node.
list1.data does not exist because it's a linkList object. See the definition of your linkList class. It has no member other than self.Head.
Your merging strategy is wrong.
mergeTwoSortedLinkListOptimize should be a separate utility function and should not be a member of linkList class because its job is to combine two linkList objects. So, it does not make sense to make it a member of the linkList class.
The fixed code is given below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class linkList:
def __init__(self):
self.Head = None
def insertAtBeg(self, data):
newNode = Node(data)
if self.Head == None:
self.Head = newNode
return
temp = self.Head
self.Head = newNode
self.Head.next = temp
def reverseLinkList(self):
preNode = None
currHead = self.Head
nextNode = self.Head
while currHead != None:
nextNode = currHead.next
currHead.next = preNode
preNode = currHead
currHead = nextNode
self.Head = preNode
def printLinkList(self):
if self.Head == None:
print("Link List is Empty")
else:
temp = self.Head
while temp != None:
print(temp.data, end=" ")
temp = temp.next
def mergeTwoSortedLinkListOptimize(list1: linkList, list2: linkList):
# result linked list
mergeList = linkList()
# if either linked list is None, nothing to do other than returning the
# other list
if list1 is None:
mergeList = list2
if list2 is None:
mergeList = list1
# if neither is None, we can perform some comparisons
if list1 is not None and list2 is not None:
list1_current_loc = list1.Head
list2_current_loc = list2.Head
while True:
# if at the last node (node.next is None), break
if list1_current_loc is None or list2_current_loc is None:
break
# compare and put the data in the result linked list
if list1_current_loc.data <= list2_current_loc.data:
mergeList.insertAtBeg(list1_current_loc.data)
list1_current_loc = list1_current_loc.next
else:
mergeList.insertAtBeg(list2_current_loc.data)
list2_current_loc = list2_current_loc.next
# copy over any remaining items
while list1_current_loc is not None:
mergeList.insertAtBeg(list1_current_loc.data)
list1_current_loc = list1_current_loc.next
while list2_current_loc is not None:
mergeList.insertAtBeg(list2_current_loc.data)
list2_current_loc = list2_current_loc.next
return mergeList
llist1 = linkList()
llist1.insertAtBeg(3)
llist1.insertAtBeg(5)
llist1.insertAtBeg(6)
llist1.insertAtBeg(8)
llist1.insertAtBeg(9)
llist1.insertAtBeg(10)
llist2 = linkList()
llist2.insertAtBeg(1)
llist2.insertAtBeg(6)
llist2.insertAtBeg(7)
llist2.insertAtBeg(15)
llist1.reverseLinkList()
llist2.reverseLinkList()
llist1.printLinkList()
print()
llist2.printLinkList()
print()
llist1 = mergeTwoSortedLinkListOptimize(llist1, llist2)
llist1.printLinkList()

TypeError: missing 1 required positional argument (LinkedList)

The problem I have is with my linked list implementation, it simply does not want to recognize my argument. Let me show you the code to illustrate what I mean:
class Node:
def __init__(self, element:int):
self.element = element
element:int = 0
nextNode = None
class LinkedList:
head:Node = None
def insert(self, element:int):
if self.head == None:
currentNode = Node.__init__(element)
self.head = currentNode
else:
currentNode = self.head
while currentNode.nextNode != None:
currentNode = currentNode.nextNode
newNode = Node.__init__(element)
currentNode.nextNode = newNode
def prettyPrint(self):
currentNode = self.head
print("Current Linked List\n")
while currentNode.nextNode != None:
print(currentNode.element+" ---> ")
currentNode = currentNode.nextNode
def main():
Linkedlist = LinkedList()
Linkedlist.insert(1)
Linkedlist.insert(9)
Linkedlist.insert(2)
Linkedlist.insert(18)
Linkedlist.insert(5)
Linkedlist.insert(8)
Linkedlist.prettyPrint()
if __name__ == '__main__':
main()
The error happens in the insert method at
currentNode = Node.init(element)
I'm new to Python and so any help is appreciated.
Here is your code with two small fixes:
Construct a Node by calling Node(element)
in print either separate arguments with a , or use end="something" to tell print to put a "something" at the end of the output.
class Node:
def __init__(self, element: int):
self.element = element
element: int = 0
nextNode = None
class LinkedList:
head: Node = None
def insert(self, element: int):
if self.head == None:
currentNode = Node(element)
self.head = currentNode
else:
currentNode = self.head
while currentNode.nextNode != None:
currentNode = currentNode.nextNode
newNode = Node(element)
currentNode.nextNode = newNode
def prettyPrint(self):
currentNode = self.head
print("Current Linked List\n")
while currentNode.nextNode != None:
print(currentNode.element, end=" ---> ")
currentNode = currentNode.nextNode
def main():
Linkedlist = LinkedList()
Linkedlist.insert(1)
Linkedlist.insert(9)
Linkedlist.insert(2)
Linkedlist.insert(18)
Linkedlist.insert(5)
Linkedlist.insert(8)
Linkedlist.prettyPrint()
if __name__ == "__main__":
main()
Have fun learning python ;)
As I mentioned in the comment, replace currentNode = Node.__init__(element) with currentNode = Node(element).
Also, I would recommend to change your Node class to something like this.
class Node:
def __init__(self, element:int):
self.element = element
self.nextNode = None
Furthermore there are another issues in your prettyPrint() method.
First, you will get TypeError because of line, print(currentNode.element+" ---> ").
Second, you are not printing the last element of the linked list. So, add print(currentNode.element) after the while loop.
So, I would change it to something like this to get your desired output.
def prettyPrint(self):
currentNode = self.head
print("Current Linked List\n")
while currentNode.nextNode != None:
print(currentNode.element, end=' ---> ')
currentNode = currentNode.nextNode
print(currentNode.element)

calling a method in another method errors

class Node:
def __init__(self, data):
self.data = data
self.ref = None
class LinkedList:
def __init__(self):
self.head = None
def show(self):
if self.head is None:
print("This linked lists is empty")
else:
currentnode = self.head
while currentnode is not None:
print(currentnode.data, end=" --> ")
currentnode = currentnode.ref
def addelement(self, value):
newnode = Node(value)
newnode.ref = self.head
self.head = newnode
def lenofll(self , i = 0):
while self.head is not None:
i = i +1
self.head = self.head.ref
return i
def middle(self):
i = 0
lent = self.lenofll()
if self.head is None: # self.head changed to None after calling lenofll method.
print("linked list is empty")
I wanted to get the length of linked lists in the middle method. But as I called self.lenofll(), it changed the self.head to None.
What can I do to fix this?
Indeed, doing self.head = self.head.ref modifies the head. You should not make any modifications to self.head in a method whose job is just to search in the list -- without modifying anything to it.
As you can see, that method keeps looping until self.head is not None is not true, i.e. when self.head is None. No wonder that self.head is None after running this method!
Use a local variable for this iteration instead:
def lenofll(self, i = 0):
node = self.head # use local variable
while node is not None:
i += 1
node = node.ref
return i

Merging Multiple sorted linkedlists into One

I am trying to write a program to merge two sorted linked lists.
But its not merging them.
it seems like the error is in representing head pointer.
how to represent head pointer? is my way correct.
I am facing a lot of problems using pointers pls give me some suggestions especially head pointer
merge two sorted linkedlist
class Node:
def __init__(self,data):
self.data=data
self.next =None
class linkedlist:
def __init__(self):
self.head=None
def push(self,ndata):
nnode = Node(ndata)
nnode.next = self.head
self.head = nnode
def addNodeToList(self,ndata):
nnode = Node(ndata)
if self.head is None:
self.head = nnode
return
last = self.head
while last.next is not None:
last = last.next
last.next = nnode
def printList(self):
temp = self.head
while temp is not None:
print(temp.data,end = ' ')
temp = temp.next
def merge(first,second):
dummy=linkedlist()
temp = dummy.head
temp1=first.head
temp2=second.head
while temp1 and temp2:
if temp1.data<temp2.data:
temp=temp1
temp.next=None
temp1=temp1.next
print('\n1..')
elif temp1.data>=temp2.data:
temp=temp2
temp.next=None
temp2=temp2.next
print('\n2..')
if temp1 is not None:
temp.next= temp1
print('\n3..')
else:
temp.next=temp2
print('\n4..')
print('Done')
return dummy
if __name__=='__main__':
list1=linkedlist()
list1.addNodeToList(10)
list1.addNodeToList(20)
list1.addNodeToList(30)
list1.addNodeToList(40)
list1.addNodeToList(50)
list2=linkedlist()
# Create linked list 2 : 5->15->18->35->60
list2.addNodeToList(5)
list2.addNodeToList(15)
list2.addNodeToList(18)
list2.addNodeToList(35)
list2.addNodeToList(60)
list1.printList()
print()
list2.printList()
a=merge(list1,list2)
a.printList()
Expected output is a single merged linkedlist
You already have the addNodeToList() function so why not use it?
def merge(first,second):
dummy=linkedlist()
temp1=first.head
temp2=second.head
while temp1 and temp2:
if temp1.data<temp2.data:
dummy.addNodeToList(temp1.data)
temp1=temp1.next
else:
dummy.addNodeToList(temp2.data)
temp2=temp2.next
while temp1:
dummy.addNodeToList(temp1.data)
temp1=temp1.next
while temp2:
dummy.addNodeToList(temp2.data)
temp2=temp2.next
return dummy
You are never adding to dummy in your code - you do temp = dummy.head and then you reassign temp and the dummy list is never updated. Here is an approach:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList: # classes in python must be in CamelCase
def __init__(self):
self.head = None
def push(self, ndata):
nnode = Node(ndata)
nnode.next = self.head
self.head = nnode
def addNodeToList(self, ndata):
nnode = Node(ndata)
if self.head is None:
self.head = nnode
return
last = self.head
while last.next is not None:
last = last.next
last.next = nnode
def printList(self):
temp = self.head
while temp is not None:
print(temp.data, end = ' ')
temp = temp.next
def walk_list(self):
temp = self.head
values = []
while temp is not None:
values.append(temp.data)
temp = temp.next
return values
def merge(first, second):
values1 = first.walk_list()
values1.extend(second.walk_list())
dummy = LinkedList()
for v in sorted(values1):
dummy.push(v)
return dummy
if __name__ == '__main__':
list1 = LinkedList()
list1.addNodeToList(10)
list1.addNodeToList(20)
list1.addNodeToList(30)
list1.addNodeToList(40)
list1.addNodeToList(50)
list2 = LinkedList()
# Create linked list 2 : 5->15->18->35->60
list2.addNodeToList(5)
list2.addNodeToList(15)
list2.addNodeToList(18)
list2.addNodeToList(35)
list2.addNodeToList(60)
list1.printList()
print()
list2.printList()
a = merge(list1, list2)
a.printList()

Python insert node function

I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print current.data,
current = current.next
def insert(self, head, data):
self.head = head
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
mylist.display(head)
Your insert() didn't return anything. So head will be None if you assign returned value to it.
I think this is you want
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def __init__(self):
self.head = None
def display(self):
current = self.head
while current:
print current.data,
current = current.next
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
for i in range(T):
data = int(input())
mylist.insert(data)
mylist.display()

Categories