86. 分隔链表

自己做

解:双指针法
/*** 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* p = head;ListNode* q = head;ListNode* r1 = head;ListNode* r2 = head;while(q != nullptr && q->val < x){ //分割线p = q; //分割线前一位q = q->next;r1 = q; //移动结点前一位if(q != nullptr)r2 = q->next; //移动结点elser2 = q; //如果q为空说明这个链表的边界就是末尾}while(r2 != nullptr){if(r2->val < x){ //找到要移动的目标值if(q == head){ //在头结点前插入,涉及头结点的更改head = r2;r1->next = r2->next;r2->next = q;p = head;r2 = r1->next;}else{p->next = r2;r1->next = r2->next;r2->next = q;p = p->next;r2 = r1->next;}}else{ //继续找r1 = r2;r2 = r2->next;}}return head;}};