-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListPalindrome.java
42 lines (36 loc) · 1.11 KB
/
LinkedListPalindrome.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
import java.util.*;
class Program {
// This is an input class. Do not edit.
public static class LinkedList {
public int value;
public LinkedList next;
public LinkedList(int value) {
this.value = value;
this.next = null;
}
}
// O(n) time | O(n) space
public boolean linkedListPalindrome(LinkedList head) {
// Write your code here.
return isPalindrome(head, head).first;
}
private Pair<Boolean, LinkedList> isPalindrome(LinkedList leftNode, LinkedList rightNode) {
if (rightNode == null) {
return new Pair<>(true, leftNode);
}
Pair<Boolean, LinkedList> pairInfo = isPalindrome(leftNode, rightNode.next);
boolean outerNodesAreEqual = pairInfo.first;
LinkedList leftNodeToCompare = pairInfo.second;
boolean recursiveIsEqual = outerNodesAreEqual && (leftNodeToCompare.value == rightNode.value);
LinkedList nextLeftNodeToCompare = leftNodeToCompare.next;
return new Pair<>(recursiveIsEqual, nextLeftNodeToCompare);
}
class Pair<U, V> {
public U first;
public V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
}
}