[Leetcode] 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.

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

Solution:

  1. 从左往右扫描,找到第一个大于X的指针,然后再该指针左边,不断插入小于X的元素。这里为了避免处理head是否为空的检测,在头指针位置先插入一个干扰元素,以保证head永不为空,然后在最后返回的时候删除掉。
  2. 用small来指向比x小的值的最后一个,用big来指向大于或等于x的值的最后一个,即下一个应该插入的位置。
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode partition(ListNode head, int x) {
14         ListNode root=new ListNode(-1);
15         root.next=head;
16         ListNode small=root;
17         ListNode big=root;
18         ListNode pointer=root;
19         while(pointer.next!=null){                     //在这里找第一个比x大或等的数
20             if(pointer.next.val>=x){
21                 small=pointer;
22                 big=pointer.next;
23                 pointer=pointer.next;
24                 break;
25             }
26             pointer=pointer.next;
27         }
28         while(pointer.next!=null){
29             if(pointer.next.val>=x){
30                 pointer=pointer.next;
31                 big=big.next;
32             }else{
33                 pointer=pointer.next;
34                 ListNode temp=pointer.next;
35                 pointer.next=small.next;
36                 small.next=pointer;
37                 big.next=temp;
38                 pointer=big;
39                 small=small.next;
40             }
41         }
42         return root.next;
43     }
44 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4101017.html