forked from careercup/ctci
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestionB.java
More file actions
58 lines (47 loc) · 1.35 KB
/
QuestionB.java
File metadata and controls
58 lines (47 loc) · 1.35 KB
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
package Question2_7;
import CtCILibrary.LinkedListNode;
import java.util.Stack;
public class QuestionB {
public static boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;
Stack<Integer> stack = new Stack<Integer>();
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
/* Has odd number of elements, so skip the middle */
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
int top = stack.pop().intValue();
System.out.println(slow.data + " " + top);
if (top != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}
public static void main(String[] args) {
int length = 9;
LinkedListNode[] nodes = new LinkedListNode[length];
for (int i = 0; i < length; i++) {
nodes[i] = new LinkedListNode(i >= length / 2 ? length - i - 1 : i, null, null);
}
for (int i = 0; i < length; i++) {
if (i < length - 1) {
nodes[i].setNext(nodes[i + 1]);
}
if (i > 0) {
nodes[i].setPrevious(nodes[i - 1]);
}
}
//nodes[length - 2].data = 9; // Uncomment to ruin palindrome
LinkedListNode head = nodes[0];
System.out.println(head.printForward());
System.out.println(isPalindrome(head));
}
}