86题 分割链表
思路: 新建两个链表,两个初始为哑节点,before存放小于x的节点,after存放大于等于x的节点。遍历head链表,最后p2后面记得指向null,p1.next=after.next,返回before.next.
时间复杂度分析: O(n)
/**
* 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 before=new ListNode(0);
ListNode after =new ListNode(0);
ListNode p1=before;
ListNode p2=after;
while(head!=null){
if(head.val<x){
p1.next=head;//为什么这里p1加了一个head,before那里也会加吗?before不会动的吗?
p1=p1.next;
}
else if(head.val>=x){
p2.next=head;
p2=p2.next;
}
head=head.next;
}
p2.next=null;
p1.next=after.next;
return before.next;
}
}