'Linked list value double_up() method causing TypeError
I am trying to implement a linked list in python and trying to create a method that doubles the value of each element in the linked list. This method updates the LinkedList object and it does not return anything.
I'm getting a TypeError: unsupported operand type(s) for *: 'Node' and 'int'.
Would anybody able to give me some tips on how to fix it?
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
class LinkedList:
def __init__(self):
self.head = None
self.count = 0
def add(self, item):
new_node = Node(item, self.head)
self.head = new_node
self.count += 1
def is_empty(self):
return self.count == 0
def size(self):
return self.count
def search(self, item):
current = self.head
while current:
if current.data == item:
return True
current = current.next
return False
def remove(self, item): #change this method to update self.count
found = False
current = self.head
previous = None
while current is not None and not found:
if current.data == item:
found = True
else:
previous = current
current = current.next
if found:
if previous == None:
self.head= current.next
else:
previous.set_next(current.next)
self.count -= 1
def count(self):
return len(self)
def __str__(self):
new_str = ""
if self.count != 0:
curr = self.head
while curr is not None:
new_str += str(curr.data) + " -> "
curr = curr.next
new_str += "None"
return new_str
def remove_from_head(self):
data = self.head.data
self.head = self.head.next
self.count -=1
return data
def double_up(self):
while self.head.data != None:
self.head.data = self.head.data * 2
self.head.data = self.head.next
fruit = LinkedList()
fruit.add('cherry')
fruit.add('banana')
fruit.add('apple')
print(fruit)
fruit.double_up()
print(fruit)
Expected output:
apple -> banana -> cherry -> None
appleapple -> bananabanana -> cherrycherry -> None
Solution 1:[1]
The problem is you're not traversing the linked list properly — you need to do it similarly to how the search() and remove() methods do it — i.e. like so:
def double_up(self):
current = self.head
while current is not None:
current.data = current.data * 2
current = current.next
Note you could write the while loop as shown below, which is a little more succinct:
while current:
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
