思路
题目中没有要求在原链表上进行操作,因此可以建立一大一小两个链表。
方法
新建两个链表:small和large。遍历给定链表将节点逐一挂在新建的两个链表上,注意最后对两个链表合并时的处理。
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* small = new ListNode(-1);
ListNode* large = new ListNode(-1);
ListNode* smallHead = small;
ListNode* largeHead = large;
while (head != nullptr) {
if (head -> val < x) {
small -> next = head;
small = small -> next;
}
else {
large -> next = head;
large = large -> next;
}
head = head -> next;
}
large -> next = nullptr;
small -> next = largeHead -> next;
return smallHead -> next;
}
};