-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIsPalindrome.java
56 lines (49 loc) · 1.48 KB
/
IsPalindrome.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
package main.java.topcodingquestion.linkedlist;
import main.java.ctci.datastructure.LinkedListNode;
import java.util.Stack;
public class IsPalindrome {
Node left;
public boolean isPalindrome(Node head) {
left = head;
boolean result = helper(head);
return result;
}
private boolean helper(Node right) {
if (right == null) {
return true;
}
boolean x = helper(right.next);
if (!x) {
return false;
}
boolean result = (left.val == right.val);
left = left.next;
return result;
}
public boolean checkPalindrome(LinkedListNode head) {
LinkedListNode slow = head;
LinkedListNode fast = head;
Stack<Integer> stack = new Stack<>();
/*
Push the element from the first half of linked list onto stack when fast pointer
reaches the end of the linked list,then slow pointer will at the middle
*/
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next; //2x speed
}
//has odd number of elements, so skip the middle element
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
int data = stack.pop().intValue();
if (data != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}
}