2130. 链表最大孪生和

题目描述:

在这里插入图片描述

主要思路:

本题可以拆解为:找链表中点(快慢指针)+翻转后边链表。

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_54385104/article/details/132115879