当前位置:首页 > 编程笔记 > 正文
已解决

力扣:143. 重排链表(Python3)

来自网友在路上 164864提问 提问时间:2023-10-28 22:55:36阅读次数: 64

最佳答案 问答题库648位专家为你答疑解惑

题目:

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:head = [1,2,3,4]
输出:[1,4,2,3]


示例 2:

输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]

解法:

链表转列表,依次从尾从头弹出结点,连接到head,head最后指向空。

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reorderList(self, head: Optional[ListNode]) -> None:"""Do not return anything, modify head in-place instead."""nodes = []point = head.nextwhile point:nodes.append(point)point = point.nextindex = 0while nodes:if index % 2 == 0:head.next = nodes.pop()else:head.next = nodes.pop(0)head = head.nextindex += 1head.next = None

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"力扣:143. 重排链表(Python3)":http://eshow365.cn/6-27165-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!