Leetcode 234 回文链表,双指针与快慢指针

  双指针解法为两个指针,一个指向头元素,一个指向尾元素。两个指针逐步向中间靠拢并比较路过的元素:

复制代码
 /**
     * @Author Niuxy
     * @Date 2020/6/23 8:22 下午
     * @Description 双指针
     */
    public final boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode temp = head;
        //链表长度
        int length = 1;
        while (temp.next != null) {
            temp = temp.next;
            length++;
        }
        //双指针
        int before = 0;
        int after = length - 1;
        while (after > before) {
            if (getNode(head, before).val != getNode(head, after).val) {
                return false;
            }
            before++;
            after--;
        }
        return true;
    }

    private final ListNode getNode(ListNode head, int index) {
        while (index != 0) {
            head = head.next;
            index--;
        }
        return head;
    }
复制代码

  快慢指针解法为通过快慢指针找到中点,从中点断开链表。翻转其中一个链表后,比较两个链表是否相同:

复制代码
 /**
     * @Author Niuxy
     * @Date 2020/6/23 8:22 下午
     * @Description 快慢指针翻转链表
     */
    public final boolean isPalindrome2(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head.next.next;
        //快慢指针找中点
        while (fast != null && fast.next != null) {
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode seHead=revoleList(slow.next);
        slow.next=null;
        ListNode fiHead=head;
        while(fiHead!=null&&seHead!=null){
            if(fiHead.val!=seHead.val){
                return false;
            }
            fiHead=fiHead.next;
            seHead=seHead.next;
        }
        return true;
    }

    //翻转链表
    private static ListNode revoleList(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode next = head.next.next;
        ListNode node = head.next;
        ListNode pre = head;
        head.next = null;
        while (node != null) {
            node.next = pre;
            if (next == null) {
                return node;
            }
            pre = node;
            node = next;
            next = next.next;
        }
        return node;
    }
复制代码

  两种解法均有空间复杂度为 O(1) 的实现方式,快慢指针解法耗时更少:

 

posted @   牛有肉  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示