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
.
根据x,将小于x的节点放在大于x节点的前面。。
正常思路就行:新建两个链表,一个存放大于x的,一个存放小于x的。最后连接起来。注意写代码的一些细节。最后节点(大链表的最后一个)的next要设为null
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null||head.next==null) return head;
ListNode small=new ListNode(0);
ListNode big=new ListNode(0);
ListNode s=small,b=big; //用来遍历添加节点
while(head!=null){
if(head.val>=x){
b.next=head;
b=b.next;
}else{
s.next=head;
s=s.next;
}
head=head.next;
}
b.next=null; //大的最后一个节点的next要设为null,这一步一定不能忘记。不然它还是会指向原来的next。
s.next=big.next;
return small.next;
}
}