链表的基础操作(二)

回文链表

简单描述就是 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个参数,见下图所示。然后来遍历链表,将这三种条件放到不同的位置,注意头指向尾部,最终如第二张图所示,进行串联起来,注意其中串联起来的节点有的为空的场景哦。

相关推荐
拂拉氏1 小时前
【知识讲解】 红黑树的删除讲解
数据结构·算法·红黑树
初学者,亦行者1 小时前
算法设计与分析:动态规划 - TSP问题和0-1背包问题
c++·算法·动态规划
ward RINL1 小时前
# GPT-5.6-sol vs GPT-5.5 新题实测:非弹性碰撞物理题和稳定路由算法
网络·gpt·算法
灯澜忆梦1 小时前
【dp_1】爬楼梯 | 斐波那契数 | 第 N 个泰波那契数 | 三步问题
算法·golang
星释2 小时前
鸿蒙智能体开发实战:35.鸿蒙壁纸大师 - 调用火山引擎模型生成壁纸
算法·华为·ai·harmonyos·鸿蒙·火山引擎
geovindu2 小时前
go: Floyd-Warshall Algorithms
开发语言·后端·算法·golang
db_murphy2 小时前
机器学习决策树的基尼系数是个啥?
学习·算法
2301_800256112 小时前
数据结构基础hw9判断选择题、hw7编程题、hw12编程题
数据结构·算法