-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome_Linked_List.java
More file actions
39 lines (36 loc) · 967 Bytes
/
Copy pathPalindrome_Linked_List.java
File metadata and controls
39 lines (36 loc) · 967 Bytes
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
package com.leet_code;
import java.util.Stack;
public class Palindrome_Linked_List {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public boolean isPalindrome(ListNode head) {
if ( head.next==null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
Stack<Integer> st=new Stack<>();
while (fast != null && fast.next != null) {
st.push(slow.val);
slow = slow.next;
fast = fast.next.next;
}
if (fast!=null){
slow=slow.next;
}
while (slow!=null){
if (slow.val == st.peek()) {
st.pop();
}slow=slow.next;
}
if (st.empty()){
return true;
}
return false;
}
}