2.6 Palindrome

Implement a function to check if a linked list is a palindrome.

Hint
  • A palindrome is something which is the same when written forwards and backwards. What if you reversed the linked list?
  • Try using a stack.
  • Assume you have the length of the linked list. Can you implement this recursively?
  • In the recursive approach (we have the length of the list), the middle is the base case: isPermutation(middle) is true. The node x to the immediate left of the middle: What can that node do to check if x -> middle -> y forms a palindrome? Now suppose that checks out. What about the previous node a? If x -> middle -> y is a palindrome, how can it check that a -> x -> middle -> y-> b is a palindrome?
  • Go back to the previous hint. Remember: There are ways to return multiple values. You can do this with a new class.
Solution

本题让我们判断一个链表是否为回文链表,由于不能随机访问结点,因此一个直接的思路便是先把所有结点压入一个stack,然后再次遍历链表同时将结点出栈,比较两者的值是否对应相等即可。前面的方法需要遍历两次链表,我们可以进一步优化,利用快慢指针(慢指针1步,快指针2步)找到链表中点后,直接继续遍历后半段即可进行比较。

public static boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null) return true; 
    Deque<Integer> stack = new LinkedList<>();
    stack.push(head.val);   
    ListNode slow = head, fast = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        stack.push(slow.val);
    }
    if (fast.next == null) stack.pop(); // 结点数为奇数时,去掉中间结点   
    while (slow.next != null) {
        slow = slow.next;
        if (slow.val != stack.pop()) return false;
    }
    return true;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,297评论 3 20
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,940评论 0 23
  • 建国 我睁开了眼,外界的白光刹时朦胧了我的双眼,一切都恍如隔世。我此刻站在一栋大厦边,它的霓虹灯牌璀璨夺目。那是我...
    真理亞阅读 343评论 0 1
  • 对于德国的初次印象,已经渐渐融入生活了。初次到来,有许多的不适应,对于我来说,可能没有太大的差别。 早上,我们要去...
    孤影斜阳阅读 141评论 0 2