- 算法
栈 - 核心思想
因为不是部分存在回文,所以可以直接将一半放入栈中,然后依次出栈,与另外一半进行对比。需要特殊考虑的是奇偶问题。 - 代码
class Solution {
public boolean isPalindrome(ListNode head) {
int len = 0;
ListNode tempHead = head;
while(head !=null){
len++;
head = head.next;
}
if(len == 1) return true;
Stack<ListNode> st = new Stack<ListNode>();
if(len % 2 == 1){
for(int i = 0;i < len /2;i++){
st.push(tempHead);
tempHead = tempHead.next;
}
tempHead = tempHead.next;
}else{
for(int i = 0;i < len /2;i++){
st.push(tempHead);
tempHead = tempHead.next;
}
}
while(!st.isEmpty()){
if(tempHead.val != st.pop().val) return false;
else{
tempHead = tempHead.next;
}
}
return true;
}
}