leetcode -- Reorder List -- 重点,很适合作为面试题

https://leetcode.com/problems/reorder-list/

code 1

参考http://bookshadow.com/weblog/2015/01/29/leetcode-reorder-list/

思路:
1. 利用快慢指针找到链表中点mid,将链表分为左右两半
2. 将链表的右半部分就地逆置
3. 合并链表的左右两部分(一左一右的穿过所有元素

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if head and head.next and head.next.next:

            #find mid
            slow = head
            fast = head
            while fast.next and fast.next.next:
                slow = slow.next
                fast = fast.next.next
            mid = slow

            #cut in the mid
            left = head
            right = mid.next
            if right is None:
                return head
            mid.next = None

            #reverse right half
            cursor = right.next
            right.next = None
            while cursor:
                next = cursor.next
                cursor.next = right
                right = cursor
                cursor = next

            #merge left and right
            dummy = ListNode(0)
            while left or right:
                if left is not None:#注意这里的条件
                    dummy.next = left
                    left = left.next
                    dummy = dummy.next
                if right is not None:#用dummy左右穿过所有元素
                    dummy.next = right
                    right = right.next
                    dummy = dummy.next

我的递归算法,TLE超时

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 head

        cur = head
        dummy = ListNode(0)
        dummy.next = head
        pre, last = dummy, head
        while last.next:
            pre = last
            last = last.next
        pre.next = None
        tmp = cur.next
        cur.next, last.next = last, tmp
        self.reorderList(tmp)

code 2

解题思路:1,先将链表截断为两个相等长度的链表,如果链表长度为奇数,则第一条链表长度多1。如原链表为L={1,2,3,4,5},那么拆分结果为L1={1,2,3};L2={4,5}。拆分的技巧还是快慢指针的技巧。

     2,将第二条链表L2翻转,如将L2={4,5}翻转为L2={5,4}。

          3,按照题意归并链表。

http://www.cnblogs.com/zuoyuan/p/3700846.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值