回文链表

Posted by Kaka Blog on May 21, 2019

题目链接

题目

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

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:

你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

答案分析

我的答案:

/**
 * 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;
        // 计算长度
        int len = 0;
        ListNode p = head;
        while (p != null) {
            len++;
            p = p.next;
        }
        // 前部分反转
        int i = 1;
        p = head.next;
        ListNode prev = head;
        ListNode top = new ListNode(-1);
        top.next = head;
        while (i < len/2) {
            prev.next = p.next;
            p.next = top.next;
            top.next = p;
            p = prev.next;
            i++;
        }
        // ListNode q = top.next;
        // while (q != null) {
        //     System.out.println(q.val);
        //     q = q.next;
        // }
        // 快慢指针比较
        ListNode fast = p;
        if (len % 2 != 0 && fast != null)
            fast = fast.next;
        ListNode slow = top.next;
        while (fast != null) {
            if (slow.val != fast.val)
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }
}

执行用时:3 ms

别人的答案

class Solution {
    
    public boolean isPalindrome(ListNode head) {
         if(head==null||head.next==null){
            return true;
        }
        if(head.next.next==null){
            return head.val == head.next.val;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        
        while(fast.next!=null){
            if(slow.val == fast.next.val){
                if(fast.next.next!=null){
                    return false;
                }
                fast.next = null;
                slow = slow.next;
                fast = slow.next;
                if(fast==null || slow.val == fast.val){
                    return true;
                }
            }else{
                fast = fast.next;
            }
        }
        return false;
       
    }
   

}

执行用时:0 ms