我在链表中添加了4个元素,为什么只显示了3个,最后一个元素没有打印出来
I added 4 elements in the linked list, but why only three are displayed and the last element is not printed
这是我的代码。请帮我找出为什么链表的最后一个元素没有被打印出来,我怎样才能打印最后一个元素。
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def append(self, data):
current = self.head
if self.head:
while current.next:
current= current.next
current.next= data
else:
self.head = data
def show(self):
current = self.head
while current.next:
print(current.value)
current = current.next
ll1=LinkedList()
e1= Node(1)
e2 = Node(2)
e3 = Node(3)
e4 = Node(4)
ll1.append(e1)
ll1.append(e2)
ll1.append(e3)
ll1.append(e4)
ll1.show()
Image of output
因为e3.next是e4,而e4.next是None。所以 while 循环将在 e3 处结束。
只需像这样更改显示功能:
def show(self):
current = self.head
while current.next:
print(current.value)
current = current.next
if not current.next:
print(current.value)
最后一个元素没有下一个元素所以没有打印;您可以将代码更改为类似 bottom
的 do-while 格式
def show(self):
current = self.head
while True:
print(current.value)
current = current.next
if not current:
break
这是我的代码。请帮我找出为什么链表的最后一个元素没有被打印出来,我怎样才能打印最后一个元素。
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def append(self, data):
current = self.head
if self.head:
while current.next:
current= current.next
current.next= data
else:
self.head = data
def show(self):
current = self.head
while current.next:
print(current.value)
current = current.next
ll1=LinkedList()
e1= Node(1)
e2 = Node(2)
e3 = Node(3)
e4 = Node(4)
ll1.append(e1)
ll1.append(e2)
ll1.append(e3)
ll1.append(e4)
ll1.show()
Image of output
因为e3.next是e4,而e4.next是None。所以 while 循环将在 e3 处结束。
只需像这样更改显示功能:
def show(self):
current = self.head
while current.next:
print(current.value)
current = current.next
if not current.next:
print(current.value)
最后一个元素没有下一个元素所以没有打印;您可以将代码更改为类似 bottom
的 do-while 格式def show(self):
current = self.head
while True:
print(current.value)
current = current.next
if not current:
break