我试图在python中实现一个链表,并试图创建一个方法,使链表中每个元素的值加倍。这个方法更新LinkedList
对象,它不返回任何东西。
我得到一个TypeError: unsupported operand type(s) for *: 'Node' and 'int'
。有谁能给我一些修理它的建议吗?
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)
预期输出:
apple -> banana -> cherry -> None
appleapple -> bananabanana -> cherrycherry -> None
问题是你没有正确地遍历链表-你需要像search()
和remove()
方法那样做-即像这样:
def double_up(self):
current = self.head
while current is not None:
current.data = current.data * 2
current = current.next
注意,您可以像下面这样编写while
循环,这更简洁:
while current:
...