zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 10-2

    Reorder List

    要点:算法直观不多讲,这题就是实现有些细节要注意

    • 同样是前面提到的slow和fast的算法最终slow落在奇数结点中点或者偶数结点的中间右侧。所以第二步reverse的起点是slow.next:奇数很明显,偶数个,右面list的第一个结点是reverse后的最后一个结点,是不移动的
    • reverse前一定不要忘了把前后两个list分开(即set slow.next=None),否则后一个list在reverse后是没有null end的
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reorderList(self, head):
            """
            :type head: ListNode
            :rtype: void Do not return anything, modify head in-place instead.
            """
            if not head: return
            fast = slow = head
            while fast:
                fast=fast.next
                if fast:
                    fast=fast.next
                    slow=slow.next
            #print fast.val, slow.val
            
            if not slow.next: return
            cur = slow.next
            pre = None
            slow.next = None
            while cur:
                next = cur.next
                cur.next = pre
                pre = cur
                cur = next
            first = head
            second = pre
            print first.val,second.val
            while first and second:
                next = second.next
                #print next.val
                second.next = first.next
                first.next = second
                first = second.next
                second = next
            
    
  • 相关阅读:
    Max retries exceeded with ur
    DHTML【1】
    广播发送与接收
    用例图之我见
    rman catalog (rman 恢复目录)
    面试高频题:单链表的逆置操作/链表逆序
    C#3.0 语言基础扩充
    hdu 1114 Piggy-Bank(完全背包)
    VSS Get Latest Version 没有提示recursive的对话框解决
    微服务实践分享(3)服务发现
  • 原文地址:https://www.cnblogs.com/absolute/p/5675782.html
Copyright © 2011-2022 走看看