其他分享
首页 > 其他分享> > 143. Reorder List

143. Reorder List

作者:互联网

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
步骤:
1.小于等于2个节点直接返回
2.找到中间节点(参考:876. Middle of the Linked List)
3.中间节点后面的链表反转(参考:206. Reverse Linked List) 注意:记得断开中间节点后面的链表,不然链表会有环
4.把反转后的链表插入前面的链表
时间复杂度O(n), 空间复杂度O(1)
class Solution(object): 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 or not head.next.next: return fast = head slow = head pre = ListNode(None) while fast and fast.next: slow = slow.next fast = fast.next.next mid = ListNode(None) tmp = slow slow = slow.next tmp.next = None mid.next = slow while slow.next: tmp = slow.next slow.next = slow.next.next tmp.next = mid.next mid.next = tmp cur = head mid = mid.next while mid: tmp = cur.next tmp1 = mid.next mid.next = cur.next cur.next = mid cur = tmp mid = tmp1

 

标签:tmp,head,slow,143,List,mid,next,链表,Reorder
来源: https://www.cnblogs.com/boluo007/p/10334529.html