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
    
    
  • 相关阅读:
    作业:ATM
    软件开发目录规范
    re模块
    logging模块
    ConfigParser模块&hashlib模块&subprocess模块
    json模块&pickle模块&shelve模块&xml模块
    时间模块time&datetime
    vue里面render详细写法
    node.js创建服务
    vue退出功能的实现
  • 原文地址:https://www.cnblogs.com/absolute/p/5677965.html
Copyright © 2011-2022 走看看