zoukankan      html  css  js  c++  java
  • Partition List

    Partition List

    问题:

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

    You should preserve the original relative order of the nodes in each of the two partitions.

    思路:

      画画图就OK了,基本的链表操作而已

    我的代码:

    public class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head == null)    return head;
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode pre = dummy;
            while(head != null)
            {
                if(head.val >= x)   break;
                head = head.next;
                pre = pre.next;
            }
            if(head == null)    return dummy.next;
            ListNode tail = pre;
            while(head != null)
            {
                ListNode next = head.next;
                if(head.val < x)
                {
                    tail.next = head.next;
                    head.next = pre.next;
                    pre.next = head;
                    pre = head;
                }
                else
                {
                    tail = tail.next;
                }
                head = next;            
            }
            return dummy.next;
        }
    }
    View Code

    学习之处:

    • 在链表中常用的插入一个节点的方法 带插入的节点node,node之前的oriPre 待插入位置的pre,三行情书,这三行仔细想想好像某种恋爱关系,不深入展开了。这种模式要记住,免得每一次还得画图,速度变慢了。
    • origPre.next = cur.next;
      cur.next = pre.next;
      pre.next = cur;
  • 相关阅读:
    正则表达式学习1
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    (转)DBUS基础知识
    WakeLock的使用
    观察者模式
    Notification的使用
    Head First 设计模式之入门
    (转)Android WebView总结
    书架也是一根筋
    PendingIntent分析
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4336016.html
Copyright © 2011-2022 走看看