【leetcode234】回文链表 Java题解

leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势

每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解

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

示例 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) {
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        if(fast != null)
            slow = slow.next;
        slow = reverse(slow);
        fast = head;
        while(slow != null){
            if(fast.val != slow.val)
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }
    public 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;
    }
}

 思路:

  • 先一快一慢分别走到最后和中间位置
  • 如果该链表元素的个数为偶数,那么fast最后一步将会为null
  • 所以,为奇数个时,slow需要再走一步达到中间位置
  • 通过调用自定义的reverse方法重复遍历

猜你喜欢

转载自blog.csdn.net/weixin_43046082/article/details/89044388
今日推荐