leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
2130.cpp (842B)
0 class Solution { 1 ListNode *pre_mid(ListNode *head) { 2 ListNode *slow = head, *fast = head; 3 while (fast->next && fast->next->next) { 4 slow = slow->next; 5 fast = fast->next->next; 6 } 7 return slow; 8 } 9 10 ListNode *reverse(ListNode *head) { 11 ListNode *p = head, *q = nullptr, *r = nullptr; 12 while (p) { 13 r = q; 14 q = p; 15 p = p->next; 16 q->next = r; 17 } 18 return q; 19 } 20 21 public: 22 int pairSum(ListNode *head) { 23 ListNode *pre = pre_mid(head); 24 ListNode *head2 = reverse(pre->next); 25 26 int maxi = INT_MIN; 27 for (ListNode *p = head, *q = head2; q; p = p->next, q = q->next) 28 maxi = max(p->val + q->val, maxi); 29 30 pre->next = reverse(head2); 31 return maxi; 32 } 33 };