LINKED LIST

回文链表

简单#234时间 O(n)空间 O(1)力扣原题 ↗

题目

判断链表从前向后与从后向前读取是否相同。使用常数额外空间;本解法比较后恢复原链表。

示例输入head = [1,2,2,1]
示例输出true

思路

快慢指针找到前半段尾部,反转后半段后逐对比较。最后再次反转后半段,并接回原位置。

每一步都成立

比较指针分别沿前半段正向、后半段反向前进。

看它一步步执行

用的是题目示例
数组 / nums步骤 1
执行状态
这次的结果播放到最后查看

Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2    public boolean isPalindrome(ListNode head) {3        if (head == null || head.next == null) return true;4        ListNode slow = head, fast = head;5        while (fast.next != null && fast.next.next != null) {6            slow = slow.next;7            fast = fast.next.next;8        }9        ListNode second = reverse(slow.next);10        ListNode a = head, b = second;11        boolean answer = true;12        while (b != null) {13            if (a.val != b.val) answer = false;14            a = a.next; b = b.next;15        }16        slow.next = reverse(second);17        return answer;18    }19    private ListNode reverse(ListNode current) {20        ListNode prev = null;21        while (current != null) {22            ListNode next = current.next;23            current.next = prev;24            prev = current; current = next;25        }26        return prev;27    }28}
← → 单步 · 空格 播放
↑↓ 选择↵ 打开Pagefind 全文检索