zoukankan      html  css  js  c++  java
  • LeetCode234. 回文链表

    思路:【快慢指针 + 反转链表】通过快慢指针找到中间节点 ----> 切成两个链表 ----> 对后半部分进行reverse操作 -----> 依次比较前部分和后部分的值

    LeetCode143. 重排链表解法类似。

    class Solution {
        public boolean isPalindrome(ListNode head) {
            if (head == null || head.next == null) return true;
            ListNode fast = head, slow = head;
            while (fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            ListNode l2 = slow.next;
            slow.next = null;
            l2 = reverse(l2);
            while (head != null && l2 != null) {
                if (head.val != l2.val) {
                    return false;
                }
                head = head.next;
                l2 = l2.next;
            }
            return true;
        }
        private ListNode reverse(ListNode head) {
            ListNode cur = head;
            ListNode pre = null, next = null;
            while (cur != null) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    }
  • 相关阅读:
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14135698.html
Copyright © 2011-2022 走看看