首页 > 其他 > 详细

Partition List

时间:2015-03-13 22:02:09      阅读:328      评论:0      收藏:0      [点我收藏+]

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;

     

 

Partition List

原文:http://www.cnblogs.com/sunshisonghit/p/4336016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!