编写一个链表,检查链表是否为回文。
package test;
import java.util.Stack;
//又涉及从后往前遍历单链表的问题
//这是想到用栈
public class PalindromeLink {
//从可读性来讲,把所有元素入栈,再从头到尾和从未到头就可以,理解起来比较简单
public boolean isPalindrome(Node head){
Stack<Integer> st = new Stack<Integer>();
Node point = head;
while(point!=null){
st.push(point.val);
point=point.next;
}
point = head;
while(point!=null){
if(point.val != st.pop())
return false;
point=point.next;
}
return true;
}
//如果要省一半空间和时间,则比较一半元素就可以了
public boolean isPalindrome(Node head){
Stack<Integer> st = new Stack<Integer>();
Node fast = head;
Node slow = head;
while(fast!=null && fast.next!=null){
st.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
//奇数个结点
if(fast != null){
slow = slow.next;//跳过中间结点
}
while(slow!=null){
if(slow.val != st.pop())
return false;
slow = slow.next;
}
return true;
}
}