LeetCode65|回文链表

时间:2022-07-26
本文章向大家介绍LeetCode65|回文链表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

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

2,示例

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

3,题解思路

双指针的使用

4,题解程序


import java.util.ArrayList;
import java.util.List;

public class IsPalindromeTest3 {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(2);
        ListNode listNode4 = new ListNode(1);
        listNode.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        boolean palindrome = isPalindrome2(listNode);
        System.out.println("palindrome = " + palindrome);


    }

    public static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int i = 0;
        int j = list.size() - 1;
        while (i < j) {
            if (list.get(i).intValue() != list.get(j).intValue()) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    public static boolean isPalindrome2(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode slow = dummyNode;
        ListNode fast = dummyNode;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        fast = slow.next;
        slow.next = null;
        slow = dummyNode.next;

        //链表反转操作
        ListNode preNode = reverse(fast);
        while (preNode != null) {
            if (slow.val != preNode.val) {
                return false;
            }
            slow = slow.next;
            preNode = preNode.next;
        }
        return true;
    }

    private static ListNode reverse(ListNode head) {
        //前一个节点
        ListNode preNode = null;
        //当前节点
        ListNode curNode = head;
        //下一个节点
        ListNode nextNode;
        while (curNode != null) {
            //指向下一个节点
            nextNode = curNode.next;
            //将当前节点next域指向前一个节点
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
        }
        return preNode;
    }
}

5,题解程序图片版

6,总结

双指针的使用