题目:
给定一个单链表
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.next while point: nodes.append(point) point = point.next index = 0 while nodes: if index % 2 == 0: head.next = nodes.pop() else: head.next = nodes.pop(0) head = head.next index += 1 head.next = None