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

    Partition List

    要点:这题的循环条件要用cur.next,why?如果用cur,要维护两个pre,比较麻烦,而用cur.next,cur就是pre了。另一个好处是如果cur.next为null,只有一个结点不需要移动任何结点。
    还有一个特殊条件是判断lastcur,这样不移动。凡是有边界指针的题,都需要考虑这个(比如insertion sort list)。这里就有问题,为什么不能和不相等的情况用同样的code path呢?因为移动结点的假设是将待移动结点(即cur.next)的next连上last.next,如果lastcur,那么待移动结点和last.next是同一个,这样就接成自环了。
    错误点:

    • cur的初始点为dummy,而不是head
    • 别忘了交换结点之后lasat指针的移动
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def partition(self, head, x):
            """
            :type head: ListNode
            :type x: int
            :rtype: ListNode
            """
            dummy = ListNode(0)
            dummy.next = head
            last = dummy
            cur = dummy
            while cur and cur.next:
                if cur.next.val<x:
                    if last==cur:
                        last=last.next
                        cur=cur.next
                    else:
                        next = cur.next.next
                        cur.next.next = last.next
                        last.next = cur.next
                        cur.next = next
                        last=last.next
                else:
                    cur=cur.next
            
            return dummy.next
    
    
  • 相关阅读:
    web service
    常用的正则表达式
    xml
    sql helper
    sql server 表连接
    asp.net页面生命周期
    创建简单的ajax对象
    checkbox选中问题
    ES6之扩展运算符 三个点(...)
    Object.assign()的用法 -- 用于将所有可枚举属性的值从一个或多个源对象复制到目标对象,返回目标对象
  • 原文地址:https://www.cnblogs.com/absolute/p/5677965.html
Copyright © 2011-2022 走看看