Unable to append to a linked list in python - python

I'm trying to learn how to create linked lists. This is my first time doing this and the reason of code failure may be something basic I'm missing.
That being said, I am unable to figure out even after using vs code's debugger. It simply stops at the end of the append method when it is called the second time.
I am using recursion to traverse to the tail. Could that be a the problem?
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next = next_node
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
if not self.head:
return 'Linked list is empty'
linked_list = self.head.data
if self.head.next == None:
return linked_list
current = self.head
while current.next != None:
linked_list += '\n|\nV' + current.data
return linked_list
def append(self, value):
if not self.head:
self.head = Node(data=value)
return
tail = self.tail()
tail.next = Node(data=value)
def tail(self):
tail = self._traverse_to_tail(self.head)
while tail.next != None:
tail = self._traverse_to_tail(tail)
return tail
def _traverse_to_tail(self, current_node, recursion_count=0):
print(current_node.data)
if recursion_count > 997:
return current_node
if current_node.next == None:
return current_node
current_node = current_node.next
recursion_count += 1
return self._traverse_to_tail(current_node, recursion_count)
if __name__ == '__main__':
ll = LinkedList()
ll.append('foo')
ll.append('baz')
print(ll)

The problem is you have an infinite loop in the __repr__() function, because you never increment current.
def __repr__(self):
if not self.head:
return 'Linked list is empty'
linked_list = self.head.data
if self.head.next == None:
return linked_list
current = self.head
while current.next != None:
current = current.next
linked_list += '\n|\nV' + current.data
return linked_list

Related

Reversed double linked list by python

why can't print reversed this double linked list by python?
always print 6 or None
please can anyone help me fast to pass this task
///////////////////////////////////////////////////////////////////////////
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.previous = prev
sample methods==>
def set_data(self, newData):
self.data = newData
def get_data(self):
return self.data
def set_next(self, newNext):
self.next = newNext
def get_next(self):
return self.next
def hasNext(self):
return self.next is not None
def set_previous(self, newprev):
self.previous = newprev
def get_previous(self):
return self.previous
def hasPrevious(self):
return self.previous is not None
class double===>
class DoubleLinkedList:
def __init__(self):
self.head = None
self.tail = None
def addAtStart(self, item):
newNode = Node(item)
if self.head is None:
self.head = self.tail = newNode
else:
newNode.set_next(self.head)
newNode.set_previous(None)
self.head.set_previous(newNode)
self.head = newNode
def size(self):
current = self.head
count = 0
while current is not None:
count += 1
current = current.get_next()
return count
here is the wrong method ==>
try to fix it without more changes
def printReverse(self):
current = self.head
while current:
temp = current.next
current.next = current.previous
current.previous = temp
current = current.previous
temp = self.head
self.head = self.tail
self.tail = temp
print("Nodes of doubly linked list reversed: ")
while current is not None:
print(current.data),
current = current.get_next()
call methods==>
new = DoubleLinkedList()
new.addAtStart(1)
new.addAtStart(2)
new.addAtStart(3)
new.printReverse()
Your printReverse seems to do something else than what its name suggests. I would think that this function would just iterate the list nodes in reversed order and print the values, but it actually reverses the list, and doesn't print the result because of a bug.
The error in your code is that the final loop has a condition that is guaranteed to be false. current is always None when it reaches that loop, so nothing gets printed there. This is easily fixed by initialising current just before the loop with:
current = self.head
That fixes your issue, but it is not nice to have a function that both reverses the list, and prints it. It is better practice to separate these two tasks. The method that reverses the list could be named reverse. Then add another method that allows iteration of the values in the list. This is done by defining __iter__. The caller can then easily print the list with that iterator.
Here is how that looks:
def reverse(self):
current = self.head
while current:
current.previous, current.next = current.next, current.previous
current = current.previous
self.head, self.tail = self.tail, self.head
def __iter__(self):
node = self.head
while node:
yield node.data
node = node.next
def __repr__(self):
return "->".join(map(repr, self))
The main program can then be:
lst = DoubleLinkedList()
lst.addAtStart(1)
lst.addAtStart(2)
lst.addAtStart(3)
print(lst)
lst.reverse()
print(lst)

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

Implementing a LinkedList in Python - Is leetcode wrong?

I'm working on this problem: https://leetcode.com/explore/learn/card/linked-list/209/singly-linked-list/1290/
and leetcode is telling me that my code is throwing a runtime error. The input it's trying to make my code run is this:
["MyLinkedList","addAtHead","deleteAtIndex","addAtHead","addAtHead","addAtHead","addAtHead","addAtHead","addAtTail","get","deleteAtIndex","deleteAtIndex"]
[[],[2],[1],[2],[7],[3],[2],[5],[5],[5],[6],[4]]
Where the first array contains the function name and the second contains the function parameters. E.g. the second element adds a 2 at the head of the linkedlist. My question is that how would it be OK to be deleting the element at index 1 when there is only one element in the linkedlist? Is there some special thing about linked lists that I should know or is the input case incorrect. Below is my code for reference.
class SinglyLinkedList():
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def get(self, index):
if index<0 or index>self.length: raise AssertionError("get index must be in bounds")
node = self.head
for _ in range(index):
node = node.next
return node
def addAtHead(self, val):
node = SinglyListNode(val)
if self.length==0:
self.head = node
self.tail = self.head
else:
node.next = self.head
self.head = node
self.length+=1
def addAtTail(self, val):
node = SinglyListNode(val)
if self.length==0:
self.tail = node
self.head = self.tail
else:
self.tail.next = node
self.tail = node
self.length+=1
def addAtIndex(self, index, val):
if index<0 or index>self.length:
raise AssertionError(f"index at which to add ({index}) is out of bounds")
if index==0:
return self.addAtHead(val)
if index==self.length:
return self.addAtTail(val)
newNode = SinglyListNode(val)
node = self.head
for _ in range(index-1):
node = node.next
newNode.next = node.next
node.next = newNode
self.length+=1
def deleteAtIndex(self, index):
if index<0 or index>self.length:
raise AssertionError(f"index at which to add ({index}) is out of bounds")
if index==0:
self.head = self.head.next
elif index==self.length-1:
self.tail=self.get(self.length-2)
else:
node = self.head
for _ in range(index-1):
node = node.next
node.next = node.next.next
self.length-=1
def __str__(self):
res = "["
node = self.head
for _ in range(self.length-1):
res += str(node)+","
node = node.next
res += str(node)+f"] ({self.length})"
return res
From https://leetcode.com/problems/design-linked-list/
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
Looks like the delete needs to be done only when the index is valid. Your code needs to handle the case when the index is invalid.

constructing a Queue linked list using only one head pointer

I'm trying to construct a Queue linked list using only a head pointer (no tail).
but i cant seem to enqueue at the end of the list.
example: at the moment the code will: c -> b -> a, however i would like reverse it a -> b -> c.
class Node:
'''A node for a linked list.'''
def __init__(self, initdata):
self.data = initdata
self.next = None
class Queue(object):
def __init__(self):
self.head = None
def enqueue(self, item):
"""Add an item onto the tail of the queue."""
if self.head == None:
temp = Node(item)
temp.next = self.head
self.head = temp
else:
current = self.head
while current != None:
current = current.next
if current == None:
temp = Node(item)
temp.next = current
current = temp
def dequeue(self):
if self.head == None:
raise IndexError("Can't dequeue from empty queue.")
else:
current_first = self.head
current = self.head.next
return current_first.data
This should do it:
class Node:
'''A node for a linked list.'''
def __init__(self, initdata):
self.data = initdata
self.next = None
class Queue(object):
def __init__(self):
self.head = None
def enqueue(self, item):
"""Add an item onto the tail of the queue."""
if self.head is None:
self.head = Node(item)
else:
current = self.head
while current.next is not None:
current = current.next
current.next = Node(item)
def dequeue(self):
if self.head is None:
raise IndexError("Can't dequeue from empty queue.")
else:
first = self.head
self.head = self.head.next
return first.data
Besides some logic fixes (we need to create a new node and store it in current.next, current is just a variable pointing to a node), note we use is operator for testing for None and Node constructor to set data (so we can create and assign new nodes without temp var).
For example:
q = Queue()
q.enqueue('a')
q.enqueue('b')
q.enqueue('c')
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
Outputs:
a
b
c
Btw, note that such structure requires O(N) insertion time and O(1) deletion (pop) time. Double-ended queue (like the standard collections.deque) will do both insertion and deletion in constant time.

Python LinkedList Search

I'm writing code for a Linked List in Python and here's part of the code:
class LinkedList:
def __init__(self):
self.head = None
def search(self, n, value):
if n is None:
return False
elif n.data == value:
return True
else:
return search(n.next, value)
def append(self, new_value):
if self.head is None:
self.head = LinkedListNode(new_value)
else:
node = self.head
while node.next != None:
node = node.next
node.next = LinkedListNode(new_value)
def remove(self, position):
if position > 0:
node = self.head
l = 0
while node != position - 1:
l += 1
node = node.next
node.next = node.next.next
elif position == 0:
self.head = self.head.next
I'm just wondering how to implement the search() method? I think I have the right idea, but it's not working. Thank you!
When you call the method inside the same class, you need to qualify it with self.
def search(self, n, value):
if n is None:
return False
elif n.data == value:
return True
else:
return self.search(n.next, value) # <--
BTW, current search implementation requires user to pass n (LinkedList.head maybe). So I would make a wrapper to search from head, so user doesn't need to specify linked_list_instance.head every time:
def search_from_head(self, value):
return self.search(self.head, value)

Categories