面试必考精华版Leetcode2130.链表最大孪生和

题目:

面试必考精华版Leetcode2130.链表最大孪生和_第1张图片


 

代码(首刷看解析 day22):

class Solution {
public:
    int pairSum(ListNode* head) {
        ListNode* slow=head;
        ListNode* fast=head->next;
        while(fast->next!=nullptr){
            slow=slow->next;
            fast=fast->next->next;
        }
        
        //反转链表后半段
        ListNode* prev=slow->next;
        ListNode* cur=nullptr;
        while(prev->next){
            ListNode* t=prev->next;
            prev->next=cur;
            cur = prev;
            prev= t;
        }
        prev->next = cur;
        slow->next = prev;
        
        int ans=0;
        ListNode* x=head;
        ListNode* y=slow->next;
        while(y){
            ans=max(ans,x->val + y->val);
            x=x->next;
            y=y->next;
        }
        return ans;
    }
};

你可能感兴趣的:(#,leetcode,---medium,前端,算法,javascript)