美文网首页
234. Palindrome Linked List

234. Palindrome Linked List

作者: Nancyberry | 来源:发表于2018-06-21 02:50 被阅读0次

Description

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

Example 1:

Input: 1->2
Output: false

Example 2:

<pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 9.5px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; background-color: rgb(245, 245, 245); border: 1px solid rgb(204, 204, 204); border-radius: 4px;">Input: 1->2->2->1
Output: true</pre>

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

Solution

Fast-slow-pointer & reverse list, O(n), S(1)

把链表拆成两半,second链表做反转,然后比较first和second是否相等(注意长度可能会差一位)即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode secondHead = slow.next;
        slow.next = null;
        secondHead = reverse(secondHead);
        
        while (head != null && secondHead != null && head.val == secondHead.val) {
            head = head.next;
            secondHead = secondHead.next;
        }
        
        return head == null || secondHead == null;
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

相关文章

网友评论

      本文标题:234. Palindrome Linked List

      本文链接:https://www.haomeiwen.com/subject/ryntyftx.html