判断链表是否为回文

所谓回文,就是从前往后读和从后往前读都一样,比如 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;
}
相关推荐
惊讶的猫12 分钟前
字符串- 字符串转换整数 (atoi)
数据结构·算法
laocooon5238578861 小时前
C语言 有关指针,都要学哪些内容
c语言·数据结构·算法
liu****2 小时前
11.Linux进程信号(三)
linux·运维·服务器·数据结构·1024程序员节
AI科技星2 小时前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
MoRanzhi12035 小时前
Python 实现:从数学模型到完整控制台版《2048》游戏
数据结构·python·算法·游戏·数学建模·矩阵·2048
2401_841495645 小时前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
一只鱼^_6 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
叫我龙翔6 小时前
【数据结构】从零开始认识图论 --- 单源/多源最短路算法
数据结构·算法·图论
ysa0510307 小时前
虚拟位置映射(标签鸽
数据结构·c++·笔记·算法
Yue丶越7 小时前
【C语言】深入理解指针(二)
c语言·开发语言·数据结构·算法·排序算法