【题目】
给定一个链表的头节点head,请判断该链表是否为回文结构。如果链表长度为N,时间复杂度达到O(N),额外空间复杂度达到O(1)。
例如:
1->2->1,返回true
1->2->2->1,返回true
15->6->15,返回true
1->2->3,返回false
【解答】
第一种解法
boolean isPalindrome(Node<Integer> head) {
// 将链表的后半段放入栈中,压入完成后,再检查栈顶到栈底值出现的顺序是否和链表左半部分的值相对应
if (head == null || head.next == null) {
return true;
}
// 通过快慢指针找到链表的后半段
Node<Integer> right = head.next;
Node<Integer> fast = head;
while (right.next != null && right.next.next != null) {
right = right.next;
fast = fast.next.next;
}
Stack<Integer> stack = new Stack<Integer>();
while (right != null) {
stack.push(right.value);
right = right.next;