In my last code for removing duplicates, the method removeDup isn't working.
The last print(ll.display()) is printing the previous linked list.
I was hoping it to print only unique nodes. What am I missing in removeDups method?
I can't figure out. What is happening in the code here?
class Node:
def __init__(self,data = None):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LList:
def __init__(self):
self.head = None
def display(self):
current = self.head
node = []
while current != None:
node.append(current.data)
current = current.next
return node
def append(self, data):
elem = Node(data)
if self.head == None:
self.head = elem
else:
current = self.head
while current.next != None:
current = current.next
current.next = elem
def add_atFront(self, data):
elem = Node(data)
if self.head == None:
self.head = elem
else:
elem.next = self.head
self.head = elem
def removeDup(self):
current = self.head
previous = None
elems = []
while current != None:
if current.data in elems:
previous.next= current.next
else:
elems.append(current.data)
previous = current
current = current.next
ll= LList()
print(ll.display())
ll.append(65)
ll.append(7)
ll.add_atFront('65')
ll.add_atFront('Bare')
ll.insert('10',0)
ll.insert('7',2)
print(ll.display())
ll.removeDup()
print(ll.display())
Your removeDup works fine, the issue is that 65 and '65' are not duplicates, so you should not expect removeDup to dedup them. The same goes for 7 and '7'. Also, note you never defined the insert method, but I'll assume that's just a copy error.
Related
This is part of my doubly linked list deque python code.
The 'appendleft' function written almost similar to the 'append' function is normally output. Why is the last 'append('apple')' code not output normally in the 'Group_of_append' function?
class Node:
def __init__(self,item,prev,next):
self.item = item
self.prev = prev
self.next = next
class deque:
def __init__(self,name):
self.name = name
self.head = Node(None,None,None)
self.tail = Node(None,self.head,None)
self.head.next = self.tail
self.size = 0
def append(self,item):
current = self.head
new_node = Node(item,None,None)
while current.next != None:
current = current.next
current.next = new_node
new_node.prev = current
self.tail = new_node
self.size += 1
return
def appendleft(self,item):
current = self.tail
new_node = Node(item,None,None)
while current.prev != None:
current = current.prev
current.prev = new_node
new_node.next = current
self.head = new_node
self.size += 1
return
def print_list(self):
p = self.head
while p.next != None:
if p.item == None:
pass
else:
print(p.item,end=' ')
p = p.next
def Group_of_append(self):
print('Group_of_append')
self.append('graphe')
self.append('cherry')
self.append('apple')
self.appendleft('watermelon')
self.appendleft('strawberry')
self.print_list()
print(" ")
deq = deque('name')
deq.Group_of_append()
the result is
strawberry watermelon graphe cherry
The last append code on Group_of_append, self.append('apple') have no effect.
While defining the 'append' function, I thought that there would be no output due to one more size being insufficient.
So, I changed 'append' function on deque like this
def append(self,item):
self.size += 1
current = self.head
new_node = Node(item,None,None)
while current.next != None:
current = current.next
current.next = new_node
new_node.prev = current
self.tail = new_node
self.size += 1
return
But the result was same(still the lastest 'append' function doesn't print anything)
strawberry watermelon graphe cherry
Your appends work fine. Problem lies in your print_list function which stops when p.next is None. Which means your last element will not be printed because its next is None.
All in all, your logic for this list is very strange and could use a lot of rework, it would make finding mistakes like this one a lot easier for you. For example, this iterating through the whole list when appending even though you have both head and tail readily available in the deque object.
I'm trying to solve merge two sorted linkedlist problem using dummy head technique. For some reason I have an error coming from passing an argument to my dummy head holder. The output suppose to merge both linkedlist like this: 1-> 1-> 2-> 3-> 7-> None
I would be happy if you please guide which data needs to pass in my dummy head variable? Thanks in advance! This is the error I have:
dummy = LinkedList()
TypeError: __init__() missing 1 required positional argument: 'data
Here's my complete code:
class LinkedList:
def __init__(self, data):
self.data = data
self.next = None
def print_list(head: LinkedList) -> None:
while head:
print(head.data, end=" -> ")
head = head.next
print("None")
def merge_lists(headA, headB):
dummy = LinkedList()
curr = dummy
while headA != None and headB != None:
if headA.data < headB.data:
curr.next = headA
headA = headA.next
else:
curr.next = headB
headB = headB.next
curr = curr.next
if headA != None:
curr.next = headA
else:
curr.next = headB
return dummy.next
node1 = LinkedList(1)
node1.next = LinkedList(2)
node1.next.next = LinkedList(7)
node2 = LinkedList(1)
node2.next = LinkedList(3)
print(merge_lists(node1, node2)) # 1-> 1-> 2-> 3-> 7-> None
Since it is a dummy node, and you never ever use the data attribute of that node, you can pass anything as argument, like None:
dummy = LinkedList(None)
Alternatively, you could specify that providing an argument is optional, and define the constructor as follows:
class LinkedList:
def __init__(self, data=None):
self.data = data
self.next = None
Unrelated, but at the end of your script you have:
print(merge_lists(node1, node2))
This will print the object reference. You probably wanted to call the function you have defined for this purpose:
print_list(merge_lists(node1, node2))
If you want print to work like that, then instead of the print_list function, enrich LinkedList with an __iter__ method to ease iteration over the values in the list, and a __repr__ or __str__ method as follows:
class LinkedList:
def __init__(self, data=None):
self.data = data
self.next = None
def __iter__(self):
head = self
while head:
yield head.data
head = head.next
yield None # Optional
def __repr__(self):
return " -> ".join(map(str, self))
...and then you can do
print(merge_lists(node1, node2))
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def insertNode(self, data):
newnode = node(data)
if self.head is None:
self.head = newnode
else:
current = self.head
while current.next is not None:
current = current.next
current.next = newnode
def printLL(self):
current = self.head
while current.next is not None:
print(current.data, end='----->')
current = current.next
print(current.data, '------>None')
def sortLL(self):
arr=[]
current = self.head
while current.next is not None:
arr.append(current.data)
current = current.next
arr.append(current.data)
arr.sort()
self.head = None
for i in arr:
self.insertNode(i)
def mergeTwoSortedLL(l, l2):
current1 = l.head
current2 = l2.head
l3 = linkedList()
while current1 is not None and current2 is not None:
if current1.data < current2.data:
l3.insertNode(current1.data)
current1 = current1.next
else:
l3.insertNode(current2.data)
current2 = current2.next
if current1 is None:
while current2.next is not None:
l3.insertNode(current2.data)
current2 = current2.next
l3.insertNode(current2.data)
else:
while current1.next is not None:
l3.insertNode(current1.data)
current1 = current1.next
l3.insertNode(current1.data)
return l3
l = linkedList()
l.insertNode(9)
l.insertNode(18)
l.insertNode(11)
l.insertNode(15)
l.insertNode(1)
l.insertNode(8)
l.sortLL()
l.printLL()
l2 = linkedList()
l2.insertNode(9)
l2.insertNode(18)
l2.insertNode(11)
l2.insertNode(15)
l2.insertNode(1)
l2.insertNode(8)
l2.sortLL()
l2.printLL()
mergeTwoSortedLL(l,l2).printLL()
I'm creating my own linkedList implementation and am somehow deleting 2 nodes at once. I do not understand why. I have tried deleting different integers and it seems to really like to delete the second entry in the list.
When I don't use the delete method the list traverses correctly. This leads me to believe that I am deleting incorrectly. I am keeping track of the previous node with the place_node various.
class LinkedList:
def __init__(self):
self.head = None
def prepend(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def traversal(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
def append(self,data):
new_node = Node(data)
place_node = None
temp = self.head
while temp is not None:
place_node = temp
temp = temp.next
new_node.next = place_node.next
place_node.next = new_node
def delete(self,data):
new_node = Node(data)
temp = self.head
while temp is not None:
if temp.data == data:
break
place_node = temp
temp = temp.next
place_node.next = temp.next
class Node:
def __init__(self,data):
self.data = data
self.next = None
ehren = LinkedList()
ehren.prepend(5)
ehren.prepend(3)
ehren.prepend(8)
ehren.append(6)
print(" delete the number")
ehren.delete(6)
print("linked list***********")
ehren.traversal()
The delete method should be implemented like this:
def delete(self, data):
prev = None
temp = self.head
while temp is not None:
if temp.data == data:
if prev is None: # Handle the case when we are deleting the head which has no previous node
self.head = self.head.next
else:
prev.next = temp.next
break
prev = temp
temp = temp.next
Since this is a singly-linked-list, you need to keep track of the node before the target, and to delete means to set the next pointer of the previous node to the next pointer of the node to be deleted, thus making the selected node disappear.
learning how to make linked lists?
pls provide with better solution if possible.
added push ,insertafter ,printlist,append functions.
learning how to make linked lists?
pls provide with better solution if possible.
added push ,insertafter ,printlist,append functions.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAfter(self,prev_node,new_data):
if prev_node is None:
print('Enter valid previous node data')
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_data
def append(self,new_data):
new_node= Node(new_data)
if self.head is None:
self.head = new_node
last = self.head
#while last.next!= None:
#temp = last.next
#last =temp.next
while last.next:
last = last.next
last.next = new_node
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
if __name__ =='__main__':
llist = LinkedList()
llist.append(7)
llist.append(8)
llist.push(5)
llist.insertAfter(Node(5),6)
llist.printList()
The fix:
def append(self,new_data):
new_node= Node(new_data)
if self.head is None:
self.head = new_node
return # <- this is the fix
...
Without this return statement, you go to this newly added node and assign its .next to itself. With this circular reference, the next .append() gets into infinite loop
The problem is in the append method. When you append the first node, self.head is None, so you execute:
self.head = new_node
But then you continue trying to find the last node, which in this case will also end up being self.head:
last = self.head
#while last.next!= None:
#temp = last.next
#last =temp.next
while last.next:
last = last.next
As a result, when you execute this line:
last.next = new_node
You are effectively setting new_node.next = new_node, which causes the next call to append to go into an infinite loop.
This assignment asks us to implement the append, insert, index and pop methods for an unordered linked-list.
(What I have so far)
def main():
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def AppendNode(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
if self.tail != None:
self.tail.next = new_node
self.tail = new_node
def PrintList( self ):
node = self.head
while node != None:
print (node.data)
node = node.next
def PopNode( self, index ):
prev = None
node = self.head
i = 0
while ( node != None ) and ( i < index ):
prev = node
node = node.next
i += 1
if prev == None:
self.head = node.next
else:
prev.next = node.next
list = LinkedList()
list.AppendNode(1)
list.AppendNode(2)
list.AppendNode(3)
list.AppendNode(4)
list.PopNode(0)
list.PrintList( )
The output so far:
2
3
4
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
main()
File "<pyshell#31>", line 50, in main
list.PrintList( )
File "<pyshell#31>", line 27, in PrintList
node = node.next
AttributeError: 'Node' object has no attribute 'next'
I'm not sure why i'm getting the errors, since the code is technically working. Also any input on the insert, and index functions would be greatly appreciated.
For insert and index methods you will need another Node attribute, because you'll need to keep track of which item is on what position. Let we call it position. Your Node class will now look like this:
class Node:
def __init__(self, data, position = 0):
self.data = data
self.next_node = None
self.position = position
Retrieving index value now is easy as:
def index(self,item):
current = self.head
while current != None:
if current.data == item:
return current.position
else:
current = current.next
print ("item not present in list")
As for the list-altering methods, I would start with a simple add method which adds items to the leftmost position in the list:
def add(self,item):
temp = Node(item) #create a new node with the `item` value
temp.next = self.head #putting this new node as the first (leftmost) item in a list is a two-step process. First step is to point the new node to the old first (lefmost) value
self.head = temp #and second is to set `LinkedList` `head` attribute to point at the new node. Done!
current = self.head #now we need to correct position values of all items. We start by assigning `current` to the head of the list
self.index_correct(current) #and we'll write helper `index_correct` method to do the actual work.
current = self.head
previous = None
while current.position != self.size() - 1:
previous = current
current = current.next
current.back = previous
self.tail = current
What shall the index_correct method do? Just one thing - to traverse the list in order to correct index position of items, when we add new items (for example: add, insert etc.), or remove them (remove, pop, etc.). So here's what it should look like:
def index_correct(self, value):
position = 0
while value != None:
value.position = position
position += 1
value = value.next
It is plain simple. Now, let's implement insert method, as you requested:
def insert(self,item,position):
if position == 0:
self.add(item)
elif position > self.size():
print("position index out of range")
elif position == self.size():
self.AppendNode(item)
else:
temp = Node(item, position)
current = self.head
previous = None
while current.position != position:
previous = current
current = current.next
previous.next = temp
temp.next = current
temp.back = previous
current.back = temp
current = self.head
self.index_correct(current)
Below is the implementation that I could come up with (tested and working). It seems to be an old post, but I couldn't find the complete solution for this anywhere, so posting it here.
# add -- O(1)
# size -- O(1) & O(n)
# append -- O(1) & O(n)
# search -- O(n)
# remove -- O(n)
# index -- O(n)
# insert -- O(n)
# pop -- O(n) # can be O(1) if we use doubly linked list
# pop(k) -- O(k)
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setNext(self, newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
if self.tail is None:
self.tail = temp
self.length += 1
def ssize(self): # This is O(n)
current = self.head
count = 0
while current is not None:
count += 1
current = current.getNext()
return count
def size(self): # This is O(1)
return self.length
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
# The item is the 1st item
self.head = current.getNext()
else:
if current.getNext() is None:
self.tail = previous # in case the current tail is removed
previous.setNext(current.getNext())
self.length -= 1
def __str__(self):
current = self.head
string = '['
while current is not None:
string += str(current.getData())
if current.getNext() is not None:
string += ', '
current = current.getNext()
string += ']'
return string
def sappend(self, item): # This is O(n) time complexity
current = self.head
if current:
while current.getNext() is not None:
current = current.getNext()
current.setNext(Node(item))
else:
self.head = Node(item)
def append(self, item): # This is O(1) time complexity
temp = Node(item)
last = self.tail
if last:
last.setNext(temp)
else:
self.head = temp
self.tail = temp
self.length += 1
def insert(self, index, item):
temp = Node(item)
current = self.head
previous = None
count = 0
found = False
if index > self.length-1:
raise IndexError('List Index Out Of Range')
while current is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
self.length += 1
def index(self, item):
pos = 0
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
pos += 1
if not found:
raise ValueError('Value not present in the List')
return pos
def pop(self, index=None):
if index is None:
index = self.length-1
if index > self.length-1:
raise IndexError('List Index Out Of Range')
current = self.head
previous = None
found = False
if current:
count = 0
while current.getNext() is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
self.head = current.getNext()
if current.getNext() is None:
self.tail = current.getNext()
else:
self.tail = previous
previous.setNext(current.getNext())
self.length -= 1
return current.getData()
def insert(self,item,position):
if position==0:
self.add(item)
elif position>self.size():
print("Position index is out of range")
elif position==self.size():
self.append(item)
else:
temp=Node.Node(item,position)
current=self.head
previous=None
current_position=0
while current_position!=position:
previous=current
current=current.next
current_position+=1
previous.next=temp
temp.next=current
Notice that in the Node class you defined the "next" field as "next_node". Therefore the interpreter doesn't know "next". So, instead of node.next it should be node.next_node