python

python链表转换为list怎么实现

小亿
137
2023-12-20 00:04:17
栏目: 编程语言

要将一个链表转换为一个列表,可以使用迭代的方法依次遍历链表的节点,并将节点的值添加到列表中。下面是一个示例代码:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def linkedListToList(head):
    result = []  # 创建一个空列表用于存储链表的值
    node = head  # 从头节点开始遍历链表
    while node:  # 当节点不为空时
        result.append(node.val)  # 将节点的值添加到列表中
        node = node.next  # 移动到下一个节点
    return result

使用示例:

# 创建一个链表:1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5

# 将链表转换为列表
result = linkedListToList(head)
print(result)  # 输出:[1, 2, 3, 4, 5]

通过遍历链表的节点,依次将节点的值添加到列表中,最终获得了链表转换为的列表。

0
看了该问题的人还看了