-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeLinkedList.java
52 lines (46 loc) · 1.22 KB
/
PalindromeLinkedList.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
package linkedlist;
import java.util.Stack;
public class PalindromeLinkedList {
public static void main(String[] args) {
//
ListNode l= new ListNode(1);
l.next = new ListNode(2);
l.next.next= new ListNode(2);
l.next.next.next= new ListNode(1);
PalindromeLinkedList p = new PalindromeLinkedList();
System.out.println(p.isPalindrome(l));
}
public boolean isPalindrome(ListNode head) {
ListNode current= head;
int size=0;
while(current!=null){
size++;
current= current.next;
}
boolean even=(size%2==0);
int half= 0;
if(even)
half=size/2;
else
half=size/2 +1;
current= head;
int i=1;
Stack<Integer> st= new Stack();
while(current!=null){
if(i<=half){
if(!(!even && i==half)) {
st.push(current.val);
}
}
else{
if(st.peek() != current.val) {
return false;
}
st.pop();
}
current= current.next;
i++;
}
return st.size()==0;
}
}