码迷,mamicode.com
首页 > 编程语言 > 详细

86. Partition List java solutions

时间:2016-07-14 01:47:02      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode partition(ListNode head, int x) {
11         if(head == null) return head;
12         ListNode pre1 = new ListNode(0);
13         ListNode pre2 = new ListNode(0);
14         ListNode L1 = pre1;
15         ListNode L2 = pre2;
16         while(head != null){
17             if(head.val < x){
18                 L1.next = head;
19                 L1 = L1.next;
20             }else{
21                 L2.next = head;
22                 L2 = L2.next;
23             }
24             head = head.next;
25         }
26         L2.next = null;
27         L1.next = pre2.next;
28         return pre1.next;
29     }
30 }

 

 

86. Partition List java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5668173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!