forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
118 lines (86 loc) · 2.74 KB
/
Solution.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.ArrayList;
import java.util.List;
/**
* @author Oleg Cherednik
* @since 08.01.2019
*/
public class Solution {
public static void main(String... args) {
System.out.println(isPalindrome(singlyLinkedList(1, 4, 3, 4, 1))); // true
System.out.println(isPalindrome(singlyLinkedList(1, 4, 3, 5, 1))); // false
System.out.println(isPalindrome(doublyLinkedList(1, 4, 3, 4, 1))); // true
System.out.println(isPalindrome(doublyLinkedList(1, 4, 3, 5, 1))); // false
}
private static SingleNode singlyLinkedList(int... arr) {
SingleNode root = null;
SingleNode prev = null;
for (int val : arr) {
SingleNode node = new SingleNode(val);
if (prev != null)
prev.next = node;
prev = node;
root = root != null ? root : node;
}
return root;
}
private static DoubleNode doublyLinkedList(int... arr) {
DoubleNode root = null;
DoubleNode prev = null;
for (int val : arr) {
DoubleNode node = new DoubleNode(val);
if (prev != null) {
prev.next = node;
node.prev = prev;
}
prev = node;
root = root != null ? root : node;
}
return root;
}
public static boolean isPalindrome(SingleNode node) {
if (node == null)
return false;
if (node.next == null)
return true;
List<Integer> values = new ArrayList<>();
while (node != null) {
values.add(node.val);
node = node.next;
}
for (int i = 0, j = values.size() - 1; i < j; i++, j--)
if (values.get(i).intValue() != values.get(j).intValue())
return false;
return true;
}
public static boolean isPalindrome(DoubleNode node) {
if (node == null)
return false;
if (node.next == null)
return true;
DoubleNode lastNode = node;
while (lastNode.next != null)
lastNode = lastNode.next;
while (node != lastNode && node.next != lastNode) {
if (node.val != lastNode.val)
return false;
node = node.next;
lastNode = lastNode.prev;
}
return true;
}
private static final class SingleNode {
private final int val;
private SingleNode next;
public SingleNode(int val) {
this.val = val;
}
}
private static final class DoubleNode {
private final int val;
private DoubleNode next;
private DoubleNode prev;
public DoubleNode(int val) {
this.val = val;
}
}
}