思路:维护两个链表 small 和 large, small存储小于x的结点,large存储大于等于x的结点。遍历完原链表后,我们只要将 small 尾节点指向 large 头节点即可。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/partition-list/solution/fen-ge-lian-biao-by-leetcode-solution-7ade/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(0);
ListNode large = new ListNode(0);
ListNode smallHead = small, largeHead = large;
ListNode temp = head;
while(temp != null){
if(temp.val < x){
small.next = temp;
small = small.next;
}else{
large.next = temp;
large = large.next;
}
temp = temp.next;
}
small.next = largeHead.next;
large.next = null;
return smallHead.next;
}
}