题目描述
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
思路
建立两个链表
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* premin = new ListNode(-1);
ListNode* premax = new ListNode(-1);
ListNode* stmin = premin;
ListNode* stmax = premax;
ListNode* cur = head;
while (cur != NULL) {
if (cur->val < x) {
premin->next = cur;
premin = premin->next;
}else {
premax->next = cur;
premax = premax->next;
}
cur = cur->next;
}
premax->next = NULL;
premin->next = stmax->next;
return stmin->next;
}
};