-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMaximumTwinSumOfALinkedList.java
64 lines (56 loc) · 1.54 KB
/
MaximumTwinSumOfALinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/*/
/**
* 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) {
if (head.next.next == null) return head.val+head.next.val;
ListNode slow = head, prev = head, fast = head;
while (fast != null)
{
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
slow = reverseList(slow);
int max = 0;
while (head != null)
{
max = Math.max(max,head.val+slow.val);
head = head.next;
slow = slow.next;
}
return max;
}
private ListNode reverseList(ListNode head)
{
ListNode prev = head;
ListNode curr = head;
ListNode newList = head;
//till we are left with new elements
while (newList != null)
{
//set curr to new element
curr = newList;
//set new element to the next element
newList = curr.next;
//modify the poninter
curr.next = prev;
//move the previous pointer forward
prev = curr;
}
//remove the loop
head.next = null;
//update the head
head = curr;
return head;
}
}