Likou punch card 2021.1.3 separated linked list problem

Question:
Given you a linked list and a specific value x, please separate the linked list so that all nodes less than x appear before nodes greater than or equal to x.
You should keep the initial relative position of each node in the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

代码:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* small = new ListNode(0);
ListNode* smallHead = small;
ListNode* large = new ListNode(0);
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;
}
};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112141886