给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3. 示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
因为链表没有下标不方便操作,所以把节点都存在列表里面,然后就是循环处理节点了,参考了官方题解。
需要注意的一点就是修改后的最后一个节点的next要指向None。
# 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: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if not head: return [] list=[] length=0 while head: list.append(head) head=head.next length+=1 i,j=0,length-1 while i<j: list[i].next=list[j] i+=1 if i==j: break list[j].next=list[i] j-=1 list[i].next=None