回文:就是正序输出和逆序输出的顺序一致。
给出了两种方式(原来有三种,第三种太复杂,被我pass了)
package LinkedList;
import java.util.Stack;
/**
* @author:MindMrWang
*2017年12月4日
*:function:
*/
public class isPalindrome {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(1);
node1.next = node2;
node2.next = node3;
System.out.println(isPalinderome2(node1));
}
//使用栈来判别是否会文,将链表节点放入栈中,然后将栈中节点取出和链表进行比对
public static boolean isPalinderome1(Node head) {
Node cur = head;
Stack<Node> stack = new Stack<Node>();
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;
}
//方法二,对方法一的改进,只需要将后一半的链表放入栈即可,然后和前一半的链表值进行比对
public static boolean isPalinderome2(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(stack.pop().value != head.value) {
return false;
}
head = head.next;
}
return true;
}
}
参考书籍《程序员代码面试指南》