题目:给定一个链表的头结点head,判断该链表是否为回文结构。
例如:
1-2-1,返回true;
1-2-2-1,返回true;
15-6-15,返回true;
1-2-3,返回false;
方法一:利用栈结构实现。从头遍历链表,遍历的同时把加点一次压入栈中。因为栈为先进后出结构,所以遍历完成后,从栈顶到栈底的节点值出现顺序与原链表从头到尾出现顺序反过来。如果是回文结构值出现的次序是一样的。需要一个额外的栈结构,O(n)的空间。
public class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public boolean isPalindrome1(Node head){
Stack<Node> stack = new Stack<Node>();
Node cur = head;
while(cur!=null){
stack.push(cur);
cur=cur.next;
}
while(head!=null){
if(head.value!=stack.pop().value){
return false;
}
head = head.next;
}
return true;
}
方法二:把整个链表的右半部分压入栈中,压入完成后,在检查栈顶到栈底的值出现的顺序是否和链表的左半部分值顺序一致。
1-2-2-1,左半部分是1,2,右半部分是2,1
public boolean isPalindrome2(Node head){
if(head==null||head.next==null){return true;}
Node right = head.next;
Node cur = head;
while(cur.next!=null&&cur.next.next!=null){
right = right.next;
cur= cur.next.next;//找中间节点
}
Stack<Node> stack = new Stack<Node>();
while(right!=null){
stack.push(right);
right = right.next;//从中间节点往后开始压入栈中
}
while(!stack.isEmpty()){
if(head.value!=stack.pop().value){
return false;
}
head = head.next;
}
return true;
}