Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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
.
[解题思路]
找到第一个比x大的节点,在此节点之前插入所有小于x的节点
在头指针位置先插入一个干扰元素,以保证head永不为空,然后在最后返回的时候删除掉
链表操作,需总结
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 // Start typing your Java solution below 15 // DO NOT write main() function 16 ListNode p = new ListNode(Integer.MIN_VALUE); 17 p.next = head; 18 head = p; 19 20 ListNode pre = null; 21 while(p != null && p.val < x){ 22 pre = p; 23 p = p.next; 24 } 25 26 if(p != null){ 27 ListNode cur = pre; 28 while(p != null){ 29 if(p.val < x){ 30 pre.next = p.next; 31 ListNode tmp = cur.next; 32 cur.next = p; 33 p.next = tmp; 34 cur = cur.next; 35 p = pre; 36 } 37 pre = p; 38 p = p.next; 39 } 40 } 41 return head.next; 42 } 43 }