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
题解:链表题,设置两指针,并分配地址,因为头指针为变,这道题就是把小于x的数往前移动,刚开始第一个指针标记的首地址也就是第一个小于x的数,第二个指针标记的是第一个大于等于x的数,之后new两个工作指针,一个用来遍历小于x的数,一个用来遍历大于x的数,head用来遍历链表节点,为了维持递归维持小于x的指针一直连接head遇到小于x的数然后前进
代码:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode* head1=new ListNode(0);
ListNode* head2=new ListNode(0);
ListNode* h1=head1;
ListNode* h2=head2;
while(head){
if(head->val<x){
h1=h1->next=head;
}else h2=h2->next=head;
head=head->next;
}
h1->next=head2->next;
h2->next=nullptr;
return head1->next;
}
};