链表的基础操作(二)

回文链表

简单描述就是 1->2->3->2->1 这种结构,也就是正着念跟反着念是一样的。所以可以使用,可以使得倒过来然后再来跟正着一一比对。

java 复制代码
public boolean isPalindrome(ListNode head) {
    if (head == null) {
        return true;
    }
    Stack<ListNode> listNodeHS = new Stack<>();
    ListNode currentNode = head;
    while (currentNode != null) {
        listNodeHS.add(currentNode);
        currentNode = currentNode.next;
    }
    // 收集完毕,将全部节点压入栈中,然后遍历原有链表
    while (head != null) {
        ListNode pop = listNodeHS.pop();
        if (pop.val != head.val) { // 如果不匹配则直接返回false
            return false;
        }
        head = head.next;
    }
    return true;
}

高级版本的操作

java 复制代码
public boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null) return true;
    ListNode slow = head; // 慢指针
    ListNode fast = head; // 快指针

    while (fast.next != null && fast.next.next != null) { // 快指针走得快,注意这个条件为fast.next.next/fast.next时slow分别落到那个位置
        slow = slow.next;
        fast = fast.next.next;
    }

    // 当 fast为null时则表明数量为偶数,此时慢指针走到左中心位置此时如果在往右走一步则左侧跟右侧一致(逆序)
    // 当 fast不为null时则表明为奇数,此时slow刚好走到中间位置,此时它的右侧跟左侧是一样的。

    // 反转链表
    ListNode reverseNode = reverse(slow.next);
    while (reverseNode != null) {
        if (head.val != reverseNode.val) {
            return false;
        } else {
            head = head.next;
            reverseNode = reverseNode.next;
        }
    }
    return true;
}

private ListNode reverse(ListNode head) {
    if (head == null) {
        return null;
    }
    ListNode pre = null;
    ListNode next = null;
    while (head != null) {
        next = head.next;
        head.next = pre; // 当前节点指向前一个节点
        pre = head; // pre来到当前节点
        head = next; // head来到下一个节点
    }
    return pre;
}

fast.next.next fast.next 分别落在什么位置

分隔链表

给你一个链表的头节点 head 和一个特定值 x,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

输入:head = 1,4,3,2,5,2, x = 3 输出:1,2,2,4,3,5

思想:就是分别整6个参数,见下图所示。然后来遍历链表,将这三种条件放到不同的位置,注意头指向尾部,最终如第二张图所示,进行串联起来,注意其中串联起来的节点有的为空的场景哦。

相关推荐
数模竞赛Paid answer23 分钟前
2025年中青杯数学建模A题康养城市建设求解全过程论文及程序
算法·数学建模·数据分析·中青杯
网安蟹佬霸24 分钟前
密码学安全实战:从加密原理到哈希破解的完整攻防指南
网络·算法·安全·web安全·开源·密码学·哈希算法
yangmu320342 分钟前
深度解析:短视频是如何通过“算法+神经机制”劫持用户时间的?
算法
LuminousCPP1 小时前
栈和队列专题(四):LeetCode 232. 用栈实现队列|双栈分工 + 按需迁移 + 摊还 O(1)
c语言·数据结构·笔记·算法·leetcode
tudousisi2221 小时前
01背包8.21
数据结构·算法
ZJU_统一阿萨姆1 小时前
【算子开发】Reduction算子完全指南
人工智能·算法·语言模型
鹿角片ljp10 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技10 小时前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
.道阻且长.13 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq713 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode