给定一个单链表 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.
懒人晴把他们丢入了一个list,然后重新连接。不知道会不会被打……
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def reorderList(self, head):""":type head: ListNode:rtype: void Do not return anything, modify head in-place instead."""if not head or not head.next:returnl=[]p=headwhile p:l.append(p)p=p.nexti=1j=len(l)-2p=headp.next=l[len(l)-1]p=p.nextwhile i<j:p.next=l[i]p=p.nextp.next=l[j]p=p.nexti+=1j-=1if i==j:p.next=l[i]p=p.nextp.next=Nonereturn