给定一个链表的头节点head,请判断该链表是否为回文结构。 例如: 1->2->1,返回true。 1->2->2->1,返回true。15->6->15,返回true。 1->2->3,返回false。
import java.util.Stack;
public class e12IsPalindromeList {
public static boolean isPalindrome1(Node head) {
Node cur=head;
Stack<Node> s=new Stack<>();
while(cur!=null){
s.push(cur);
cur=cur.next;
}
while(head!=null){
if (head.value!=s.pop().value){
return false;
}
head=head.next;
}
return true;
}
public static boolean isPalindrome2(Node head){
if(head==null||head.next==null){
return true;
}
Node cur=head;
Node right=head.next;
Stack<Node> s=new Stack<>();
while(cur.next!=null&&cur.next.next!=null){
cur=cur.next.next;
right=right.next;
}
while(right!=null){
s.push(right);
right=right.next;
}
while(!s.isEmpty()){
if(s.pop().value!=head.value){
return false;
}
head=head.next;
}
return true;
}
}