文章目录

  • 234. 回文链表
  • 解题
  • 方法一:复制到数组,然后左右指针,对比
  • 方法二:反转链表


234. 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为
回文链表
。如果是,返回 true ;否则,返回 false 。

示例 1:

【NO.66】LeetCode HOT 100—234. 回文链表_反转链表

输入:head = [1,2,2,1]

输出:true

示例 2:

【NO.66】LeetCode HOT 100—234. 回文链表_链表_02

输入:head = [1,2]
输出:false

提示:

链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9

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

解题

方法一:复制到数组,然后左右指针,对比

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    // 复制到数组,然后左右指针,对比
    public boolean isPalindrome(ListNode head) {
        List<Integer> dataList = new ArrayList<>();
        ListNode curNode = head;
        while (curNode != null) {
            dataList.add(curNode.val);
            curNode = curNode.next;
        }

        // 左右指针,对比
        int left = 0;
        int right = dataList.size() - 1;
        while (left < right) {
            if (!dataList.get(left).equals(dataList.get(right))) {
                return false;
            }
            left++;
            right--;
        }

        return true;

    }
}

方法二:反转链表

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

    // 快慢指针,反转链表, 之后对比,最后还原链表
    public boolean isPalindrome(ListNode head) {
        boolean result = true;
        if (head == null) {
            return result;
        }

        // 找到前半段的最后节点
        ListNode firstHalfLastNode = endOfFirstHalf(head);
        // 反转后半段链表,并返回头节点
        ListNode secondHalfStart = reverseList(firstHalfLastNode.next);

        // 对比
        ListNode p1 = head;
        ListNode p2 = secondHalfStart;
        while(result && p2 != null) {
            if (p1.val != p2.val) {
                result = false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }

        // 还原链表,返回结果
        firstHalfLastNode.next = reverseList(secondHalfStart);
        return result;

    }

    // 反转链表(借用两个指针)
    private ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            // 复制一份
            ListNode temp = cur.next;
            // 反转指针
            cur.next = pre;
            // 指针前移
            pre = cur;
            cur = temp;
        }
        return pre;
    }


    // 找到前半段的最后节点(快慢指针)
    private ListNode endOfFirstHalf(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}