LeetCode:234. Palindrome Linked List 回文链表 Java

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Subscribe to see which companies asked this question


回文链表


题目描述

请编写一个函数,检查链表是否为回文。

给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。

测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
public class Palindrome {
    public boolean isPalindrome(ListNode pHead){
        ListNode fast = pHead;
        ListNode slow = pHead;
        Stack<Integer> stack = new Stack<Integer>();
        /**
         * 将链表的前半部分元素装入栈中,当快速runner
                 *(移动的速度是慢速runner的两倍)
         * 到底链表尾部时,则慢速runner已经处于链表中间位置
         */
        while(fast != null && fast.next != null){
            stack.push(slow.val);
            slow = slow.next;
            fast = fast.next.next;
        }
        //当链表为奇数个时,跳过中间元素
        if (fast != null) {
            slow = slow.next;
        }
        while(slow != null){
            //如果两者不相同,则该链表不是回文串
            if (stack.pop() != slow.val) {
                return false;
            }
            slow = slow.next;
        }
        return true;
    }
}





你可能感兴趣的:(java,LeetCode,li,linked,palindrome,快慢指针,回文链表)