python 链表问题
发布网友
发布时间:2022-05-25 17:33
我来回答
共1个回答
热心网友
时间:2023-11-25 05:10
class UnorderedList:
def __init__(self):
self.head = None
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def is_empty(self):
return self.head == None
def add_all(self, other_list):
for item in other_list:
self.add(item)
return self.head
def __iter__(self):
current = self.head
while current:
yield current
current = current.get_next()
def print_all(self):
for item in self:
print(item.get_data())
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
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
if __name__ == "__main__":
s = UnorderedList()
s.add(33)
s.add(44)
s.add_all([1,2,3,4])
s.print_all()
追问您好,请问需不需要强调一下while current != None。
追答class UnorderedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item).set_next(self.head)
def size(self):
current = self.head
count = 0
while current:
count = count + 1
current = current.get_next()
return count
...
class Node:
...
def set_next(self, new_next):
self.next = new_next
return self