请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解答:
public static boolean isPalindrome(ListNode head) {
if (head==null || head.next==null) return true;
ListNode slow = head, fast = head;
Stack<Integer> s = new Stack<>();
s.push(head.val);
while (fast.next!=null && fast.next.next!=null) {
slow = slow.next;
fast = fast.next.next;
s.push(slow.val);
}
if (fast.next==null) s.pop();
while (slow.next!=null) {
slow = slow.next;
int tmp = s.peek(); s.pop();
if (tmp != slow.val) return false;
}
return true;
}