[LeetCode]143. Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

Solution: 

divide the whole process to three steps:

1. find the median node 首先找出中间的结点

2. reverse the second half of the singly-linked list. (don't forget split into two lists)反转单链表的后半部分,然后将链表分成前后两个链表

3. merge these two lists. 再将两个链表合并。


Time Complexity: O(n)


Note: OJ doesn't require any return value.(No need to return the Node "head", but we should keep it there.)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param {ListNode} head
    # @return {void} Do not return anything, modify head in-place instead.
    def reorderList(self, head):
        if not head or not head.next or not head.next.next:
            return
        # find the median node
        fast = head
        slow = head
        while True:
            if fast:
                fast = fast.next
            else:
                break
            if fast:
                fast = fast.next
            else:
                break
            slow = slow.next

        # reverse the second half of the singly-linked list
        before = None
        cur = slow.next
        while cur:
            after = cur.next
            cur.next = before
            before = cur
            cur = after
        # split to two singly-linked list
        slow.next = None

        # merge two lists
        head1 = head
        head2 = before
        while head2:
            after_1 = head1.next
            after_2 = head2.next
            head1.next = head2
            head2.next = after_1
            head1 = after_1
            head2 = after_2
        return


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值