题目描述:
将所有小于x的节点放在大于等于x节点的左侧,并且保证这些节点原来的相对位置,也就是一致性
思路:
巧用临时节点
/**
* 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) {
ListNode less=new ListNode(0);
ListNode less_pre=less;
ListNode more=new ListNode(0);
ListNode more_pre=more;
while(head!=null){
if(head.val<x){
less_pre.next=head;
less_pre=less_pre.next;
}
else{
more_pre.next=head;
more_pre=more_pre.next;
}
head=head.next;
}
less_pre.next=more.next;
more_pre.next=null;
return less.next;
}
}
也就是定义两个临时头结点,一个放小于x的数,一个放大于等于x的数,然后将两个链表连接起来,返回前面小于链表 的头部的next就是我们想要的链表的头部(因为有一个头结点)