LeetCode234: Palindrome Linked List

1. 问题

问题描述:
Given the head of a singly linked list, return true if it is a palindrome.

Example 1:
example

Input: head = [1,2,2,1]
Output: true

Example 2:

Input: head = [1,2]
Output: false

Constraints:
The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9

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

2. 分析

这题最容易想到的解法是:
先从 head 遍历 list 并把值依次 pushstack 中;
然后再遍历一次 list, 和 stack 出栈结果对比, 如果都相同, 那么 此 list 就是回文链表.

题目最后提示用 O(1) 的空间复杂度.
也就是说用一个新的集合对象存 list 的数据是不可行的.

如果我们可以把 list 的 后半部分做一下翻转, 然后用两个指针分别指向 前和后 两部分, 顺序遍历一半 list, 对比每个对应的元素值是否相等, 就能知道是不是 回文链表 了.

翻转单链表:
比如把 ① -> ② -> ③ -> ④ -> ⑤
转成 ① <- ② <- ③ <- ④ <- ⑤
reverseSL
可以通过 3 个指针: cur, pre, temp 实现翻转.
上图经过5步(紫色的圈, 虚线是不存在指向关系的, 这里画出只是为了对比) 实现了翻转.

单链表中, 通过 快慢指针 找到中间位置:
变量 list , 用一个 fast 指针 每次走两步, slow 指针 每次走一步; fast 不够两步走时结束.

list.size 为奇数时: slow 会停在最中间的元素上(比如size=3, slow 会停在第2个位置上);
list.size 为偶数时: slow 会停在最中间靠前的元素上(比如 size=4, slow 也会停在第2个位置上).

不论 list.size 是奇数还是偶数, 我们在翻转后半部分单链表后, 遍历短的那一半单链表即可.

题解:

public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return false;
        }
        if (head.next == null) {
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast.next == null) {
                break;
            }
        }
        ListNode p = reverse(slow.next);
        while (p != null) {
            if (p.val != head.val) {
                return false;
            }
            p = p.next;
            head = head.next;
        }
        return true;
    }

    public ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

单链表:

// Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

3 总结

单链表是 一个基础的 数据结构.
通过 快慢指针 找单链表的中间元素,
以及 翻转单链表 都是单链表的基础操作.

这两个基础操作也是解本题的关键.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值