简单的partition,用两个链表,3个指针。
package Level4;
import Utility.ListNode;
/**
* 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.
*
*/
public class S86 {
public static void main(String[] args) {
}
public ListNode partition(ListNode head, int x) {
ListNode l1 = new ListNode(-1); // 构建dummy链表头,l1存放所有比x小的节点
ListNode l2 = new ListNode(-1);
ListNode cur = head;
ListNode l1cur = l1;
ListNode l2cur = l2;
while(cur != null){
if(cur.val < x){
l1cur.next = new ListNode(cur.val);
l1cur = l1cur.next;
}else{
l2cur.next = new ListNode(cur.val);
l2cur = l2cur.next;
}
cur = cur.next;
}
l1cur.next = l2.next; // 把两个链表合并起来
return l1.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode leftHead = new ListNode(-1);
ListNode rightHead = new ListNode(-1);
ListNode left = leftHead, right = rightHead;
while(head != null) {
if(head.val < x) {
left.next = head;
left = left.next;
} else {
right.next = head;
right = right.next;
}
head = head.next;
}
right.next = null; // Notice we need to cut off the ring
left.next = rightHead.next;
return leftHead.next;
}
}