以下是一个示例代码,用于向链表末尾添加元素:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def append_to_end(head, val):
# 创建新节点
new_node = ListNode(val)
# 如果链表为空,则新节点成为头节点
if not head:
head = new_node
return head
# 找到链表的最后一个节点
current = head
while current.next:
current = current.next
# 将新节点连接到最后一个节点
current.next = new_node
return head
使用示例:
# 创建链表 1 -> 2 -> 3 -> None
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
head.next = node2
node2.next = node3
# 添加元素 4 到链表末尾
head = append_to_end(head, 4)
# 打印链表
current = head
while current:
print(current.val)
current = current.next
输出结果:
1
2
3
4