LeetCode-回文链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zlp_zky/article/details/82625651

请判断一个链表是否为回文链表。

示例 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;
    }

猜你喜欢

转载自blog.csdn.net/zlp_zky/article/details/82625651