2130. Linked List Maximum Twin Sum

Title description:

insert image description here

Main idea:

This question can be disassembled as: find the middle point of the linked list (fast and slow pointer) + flip the back linked list.

class Solution {
    
    
public:
    int pairSum(ListNode* head) {
    
    
        ListNode* slow=head,*fast=head->next;
        while(fast->next)
        {
    
    
            slow=slow->next;
            fast=fast->next->next;
        }
        slow=slow->next;
        ListNode *l=slow,*r=slow->next;
        slow=slow->next;
        l->next=nullptr;
        while(slow)
        {
    
    
            slow=slow->next;
            r->next=l;
            l=r;
            r=slow;
        }
        int ans=0;
        while(l)
        {
    
    
            ans=max(l->val+head->val,ans);
            l=l->next;
            head=head->next;
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_54385104/article/details/132115879