[Leetcode]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}.

链表操作~先找到链表的中点,把链表切割成两段,然后反转后一段,接下来就是把两段链表合并起来,注意题目是要求in-place的~时间复杂度为O(n)

class Solution:~
    # @param head, a ListNode
    # @return nothing
    def reorderList(self, head):
        if head is None or head.next is None: return head
        slow, fast = head, head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        head1, head2 = head, slow.next
        slow.next = None
        head2 = self.reverse(head2)
        while head2:
            tmp = head1.next
            head1.next = head2
            head2 = head2.next
            head1.next.next = tmp
            head1 = head1.next.next
        
    def reverse(self, head):
        if head is None or head.next is None:
            return head
        dummy = ListNode(0)
        dummy.next = head
        pre, cur = dummy, head
        while cur.next: #made a mistake here, wrote while cur instead of while cur.next. Be careful
            tmp = cur.next
            pre.next = tmp
            cur.next = tmp.next
            tmp.next = head
            head = tmp
        return dummy.next

链表的反转部分还有其它的写法~在链表操作题中很容易遇到~

    def reverse(self, head):
        pre, cur = None, head
        while cur:
            tmp = cur.next
            cur.next= pre
            pre = cur
            cur = tmp
        return pre
链表反转还有一种递归写法~试了一下,在这里用递归的反转链表,总是TLE

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值