题目描述
解题思路
- 使用两个链表(small,large)分别存储小于x和大于x的节点
- 遍历链表,将小于x的节点插入small中,其他的插入large中
- 连接small和large,并返回。
代码实现
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(0);
ListNode smallHead = small; //记录small头
ListNode large = new ListNode(0);
ListNode largeHead = large; //记录large头
while(head != null){
if(head.val < x){ //插入small尾
small.next = head;
small = small.next;
}else{ //插入large尾
large.next = head;
large = large.next;
}
head = head.next;
}
large.next = null;
small.next = largeHead.next; //拼接small和large
return smallHead.next;
}
}