LeetCode |. 234 palindrome list


Title Description

  • Grade: 简单
    Please list to determine whether a palindrome list.

Example 1:

输入: 1->2
输出: false

Example 2:

输入: 1->2->2->1
输出: true

Advanced:
You can use O (n) time complexity and O (1) space complexity to solve this problem?

Thinking

For the 单链表, 回文, 快慢指针, 链表反转investigation.

"Palindrome" is the correct reading verlan can read through the sentence, which is at all times have a way of rhetoric and word games, such as "one for all, all for one" and so on. In mathematics, a class number is also have such features, be the number (palindrome number) palindrome. [1]
Let n is an arbitrary natural number. The resulting n1 natural number equal to n if n digits of oppositely oriented, then n is a palindrome. For example, if n = 1234321, then n is a palindrome; if n = 1234567, the number n is not a palindrome. [1]

note:

  1. There are an even number of numeric palindrome number 124 421
  2. Decimal number no palindrome

Please refer to the list reverse: reverse a singly linked list

Intermediate positions can be acquired in the linked list of nodes through two speed pointers. (Number of steps pointer speed double the difference)

answer

public boolean isPalindrome(ListNode head) {
        //1、边界检查,空链表与只有一个节点的链表直接返回true
        if (head == null || head.next == null) {
            return true;
        }

        //2、通过快慢指针找到链表中间位置
        ListNode fast = head;
        ListNode slow = head;
        //当快节点走到终点,则慢节点的位置正好为链表中间
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //fast作为后半段的起始节点
        fast = slow;
        //slow作为前半段的起始节点
        slow = head;

        //3、反转后半段链表
        //定义pre存储前一个节点
        ListNode pre = null;
        while (fast != null) {
            //指定当前要调整的点。
            ListNode temp = fast;
            //fast指针后移,走向下一个要被调整的点。
            fast = fast.next;
            //将当前的点反转
            temp.next = pre;
            //pre指针重置到最前
            pre = temp;
        }

        //4、对比前后两段链表是否相同
        //因为奇数个节点时,后半段链表比前半段链表多1个,所以循环时以前半段链表为主
        while (slow != null && pre != null) {
            if (slow.val != pre.val) {
                return false;
            }
            slow = slow.next;
            pre = pre.next;
        }
        return true;
    }

result

234.png


tencent.jpg

Guess you like

Origin www.cnblogs.com/clawhub/p/12057751.html