判断链表是否为回文

所谓回文,就是从前往后读和从后往前读都一样,比如 1→2→3→2→1 就是回文链表。

代码逻辑

1.找到链表的中点

java 复制代码
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
    slow = slow.next;
    fast = fast.next.next;
}

这里判断条件是 fast.next != null && fast.next.next != null,能保证 slow 最终停在中间偏左的位置,无论链表长度是奇数还是偶数都适用。

2.翻转后半部分链表

从中点开始,把后半部分链表反转。

反转后,链表变成了一个"双向箭头"的结构:前半部分从 head 指向中点,后半部分从尾部指向中点。

java 复制代码
ListNode pre = slow;
ListNode cur = pre.next;
ListNode next = null;
pre.next = null;  // 断开前后两部分

while (cur != null) {
    next = cur.next;      // 保存下一个节点
    cur.next = pre;       // 反转指针
    pre = cur;            // pre 前进
    cur = next;           // cur 前进
}

3.双指针比对值

现在有两个指针:left 从头开始往右走,right 从尾开始往左走。

每一步比对两个节点的值,如果不相等就说明不是回文。

java 复制代码
boolean ans = true;
ListNode left = head;
ListNode right = pre;

while (left != null && right != null) {
    if (left.val != right.val) {
        ans = false;
        break;
    }
    left = left.next;
    right = right.next;
}

4.恢复链表原状

判断完成后,不能把链表留成反转的状态,需要把后半部分再翻转回去。

java 复制代码
cur = pre.next;
pre.next = null;
while (cur != null) {
    next = cur.next;
    cur.next = pre;
    pre = cur;
    cur = next;
}

完整代码

java 复制代码
public static boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null) {
        return true;
    }
    
    ListNode slow = head, fast = head;
    // 找中点
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    // 翻转后半部分
    ListNode pre = slow;
    ListNode cur = pre.next;
    ListNode next = null;
    pre.next = null;
    while (cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    
    // 双指针比对
    boolean ans = true;
    ListNode left = head;
    ListNode right = pre;
    while (left != null && right != null) {
        if (left.val != right.val) {
            ans = false;
            break;
        }
        left = left.next;
        right = right.next;
    }
    
    // 恢复链表
    cur = pre.next;
    pre.next = null;
    while (cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    
    return ans;
}
相关推荐
2301_800256115 分钟前
B+树:数据库的基石 R树:空间数据的索引专家 四叉树:空间划分的网格大师
数据结构·数据库·b树·机器学习·postgresql·r-tree
码农幻想梦11 分钟前
第九章 高级数据结构
数据结构
AlenTech12 分钟前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表
大厂技术总监下海27 分钟前
用户行为分析怎么做?ClickHouse + 嵌套数据结构,轻松处理复杂事件
大数据·数据结构·数据库
AI科技星1 小时前
光速飞行器动力学方程的第一性原理推导、验证与范式革命
数据结构·人工智能·线性代数·算法·机器学习·概率论
余瑜鱼鱼鱼1 小时前
Java数据结构:从入门到精通(十)
数据结构
好奇龙猫1 小时前
【大学院-筆記試験練習:线性代数和数据结构(5)】
数据结构·线性代数
爱吃生蚝的于勒2 小时前
【Linux】进程间通信之匿名管道
linux·运维·服务器·c语言·数据结构·c++·vim
寻星探路2 小时前
【算法专题】哈希表:从“两数之和”到“最长连续序列”的深度解析
java·数据结构·人工智能·python·算法·ai·散列表