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;

     

 

posted on 2015-03-13 21:08  zhouzhou0615  阅读(140)  评论(0编辑  收藏  举报

导航