class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
if __name__ == '__main__':
linklist = dummy = ListNode()
for x in ([2,4,3]):
linklist .next = ListNode(x)
linklist = linklist .next
while dummy:
print(dummy.val)
dummy = dummy.next
这里的dummy 相当于是游标,每次使用链表都要单独创建一个游标指向链表头,不要直接使用链表,否则链表无法重新指向头结点
头结点默认为0
如果不要头结点0,可以像这样写
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
if __name__ == '__main__':
linklist = dummy = ListNode()
for x in ([2,4,3]):
linklist .next = ListNode(x)
linklist = linklist .next
no_head = dummy.next
while no_head:
print(no_head.val)
no_head = no_head.next