234. 回文链表

234. 回文链表

思路:快慢指针,找到中间的节点,然后将中间节点后面的(slow.next)全部reverse,然后依次比较。

注意,reverse的是slow.next后面的。

AC code。

javascript 复制代码
/**
 * 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) {
        if(head == null || head.next==null) return true;
     //   ListNode dummy = new ListNode();
       // dummy.next = head;
     //   head = dummy;
        ListNode fast=head, slow=head, slowpre = head;

        while(fast.next!=null && fast.next.next!=null){
            System.out.println("执行快慢指针时slow=" + slow.val  );
            fast = fast.next.next;
            slowpre = slow;
            slow = slow.next;
        }
        System.out.println("执行快慢指针后slow=" + slow.val );

        ListNode half = reverse(slow.next); // 这里需要是slow.next 
        slow = head;
        while(half!=null){
            //System.out.println("half=" + half.val + " slow="+slow.val);
            if(half.val != slow.val)
                return false;
            half = half.next;
            slow = slow.next;
        }
        return true;
    }
    public ListNode reverse(ListNode head){
        ListNode dummy = new ListNode();
        ListNode p = head, r=null;
        while(p!=null){
            r = p.next;
            p.next = dummy.next;
            dummy.next = p;
            p = r;
        }
        return dummy.next;
    }
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构