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?

Analysis:

1. Use slow+fast pointers to find out the median point.

2. Reverse the later half of list in-place.

3. Compare the two half lists.

4. (if needed), reverse the later half again to get the list back to original.

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head==null) return true;
        if (head.next==null) return true;
        
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode p1 = head, p2 = head;
        while (p2.next!=null && p2.next.next!=null){
            p1 = p1.next;
            p2 = p2.next.next;
        }
        
        ListNode preHead2 = p1;
        reverseList(preHead2);
        p1 = preHead.next;
        p2 = preHead2.next;
        
        while (p2!=null){
            if (p1.val!=p2.val){
                return false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        return true;
    }
    
    public void reverseList(ListNode preHead){
        ListNode cur = preHead.next;
        while (cur.next!=null){
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = preHead.next;
            preHead.next = next;
        }
    }
}

 

相关文章:

  • 2021-06-03
  • 2021-06-02
  • 2021-07-23
  • 2021-08-12
  • 2022-02-19
  • 2021-10-25
  • 2022-01-05
猜你喜欢
  • 2021-07-12
  • 2021-06-07
  • 2021-08-08
  • 2021-11-27
  • 2021-12-26
  • 2021-04-21
相关资源
相似解决方案