码迷,mamicode.com
首页 > 其他好文 > 详细

Partition List

时间:2015-03-13 22:04:02      阅读:146      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!