题目

https://leetcode.cn/problems/maximum-twin-sum-of-a-linked-list/description/
思路

- 反转整个链表,得到一个新的反转链表
- 在原始链表上用快慢指针找到中间节点
slow - 然后让原始链表的前半部分与反转链表的对应部分相加
code
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int pairSum(ListNode head) {
//反转链表
ListNode dummy=new ListNode(0,null);//反转链表的dummy节点
ListNode cur=head;
ListNode oldNode=null;
while(cur!=null){
ListNode newNode=new ListNode(cur.val,oldNode);
oldNode= newNode;
dummy.next = newNode;
cur=cur.next;
}
//找中间
ListNode fast=head;
ListNode slow=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//比大小
int max=0;
ListNode cur1=head;
ListNode cur2=dummy.next;
while(cur1!=slow){
int tmp=cur1.val+cur2.val;
if(tmp>max) max=tmp;
cur1=cur1.next;
cur2 =cur2.next;
}
return max;
}
}