[英]Python - Linked List - Append
I'm trying to learn Linked Lists in python I've been given Linked List class and asked to create append method. 我正在尝试学习python中的链接列表我已经获得了Linked List类,并要求创建append方法。
Here is the code provided. 这是提供的代码。
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item, self.head)
def remove(self):
if self.is_empty():
return None
else:
item = self.head.item
self.head = self.head.next
return item
def is_empty(self):
return self.head == None
def __str__(self):
tmp_str = ""
ptr = self.head
while ptr != None:
tmp_str += ptr.item + " "
ptr = ptr.next
return tmp_str
Here is my append method but there is something wrong with it. 这是我的追加方法,但它有问题。 I know if the Linked list is empty I have to create one, problem starts when there's elements inside.
我知道如果Linked列表是空的我必须创建一个,当里面有元素时问题就开始了。
def append(self, item):
ptr = self.head
if ptr:
while ptr != None:
ptr = ptr.next
ptr = Node(item, ptr)
else:
self.head = Node(item, self.head)
Anyone can tell me what did I do wrong please? 谁能告诉我,我做错了什么? Any help is much appreciated.
任何帮助深表感谢。
Make two checks - the first checks whether self.head
has been initialised. 进行两项检查 - 首先检查
self.head
是否已初始化。 The second should traverse the list until it finds the last node. 第二个应遍历列表,直到找到最后一个节点。 Ensure you don't overstep your boundaries, or else you won't be able to link the last node to the new last node.
确保不要超越边界,否则您将无法将最后一个节点链接到新的最后一个节点。
def append(self, item):
if not self.head:
self.head = Node(item, self.head)
else:
ptr = self.head
while ptr.next: # traverse until ptr.next is None
ptr = ptr.next
ptr.next = Node(item, ptr.next) # initialise ptr.next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.