当前位置: 首页 > news >正文

力扣刷题-热题100题-第24题(c++、python)

234. 回文链表 - 力扣(LeetCode)https://leetcode.cn/problems/palindrome-linked-list/description/?envType=study-plan-v2&envId=top-100-liked

常规法

数组是连续的存储空间,可以根据索引到达任意位置,链表只能一个个的顺着指向访问元素。最常规的方法就是将链表的元素用额外的空间存储到列表里面,看这个列表是否是回文。

//c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) 
    {
        ListNode* a=head;
        vector<int> b;
        while(a)
        {
            b.emplace_back(a->val);
            a=a->next;
        }
        for(int i=b.size()-1;i>-1;i--)
        {
            if(head->val!=b[i])    return false;
            head=head->next;
        }
        return true;
    }
};

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        a=[]
        while head:
            a.append(head.val)
            head=head.next
        return a==a[::-1]

递归法

以一个全局变量记录头指针,然后递归到链表的最后,根据递归的性质不断将头指针的下一个元素与递归的上一层进行比较。

//c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    ListNode* frontPointer;
public:
    bool a(ListNode* b)
    {
        if(b!=nullptr)
        {
            if(!a(b->next))    return false;
            if(b->val!=frontPointer->val)   return false;
            frontPointer=frontPointer->next;
        }
        return true;
    }
    bool isPalindrome(ListNode* head) 
    {
        frontPointer=head;
        return a(head);
    }
};

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        self.front_pointer=head
        
        def a(b=head):
            if b is not None:
                if not a(b.next):
                    return False
                if self.front_pointer.val!=b.val:
                    return False
                self.front_pointer=self.front_pointer.next
            return True
        return a()

改变链表

不用额外的空间,但又想判断链表,所以一次走一步,一次走两步找到中间位置(挺巧妙的),然后将中间位置往后的链表反转,直接访问元素进行判断,最后要注意恢复链表。

//c++
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* a(ListNode* b)
    {
        ListNode* pre=nullptr;
        while(b)
        {
            ListNode* nex=b->next;
            b->next=pre;
            pre=b;
            b=nex;
        }
        return pre;
    }
    bool isPalindrome(ListNode* head) 
    {
        ListNode* f=head;
        ListNode* s=head;
        while(f->next&&f->next->next)
        {
            f=f->next->next;
            s=s->next;
        }
        s=a(s);
        f=s;
        bool ans=true;
        while(head&&s)
        {
            if(head->val!=s->val)   ans=false;
            head=head->next;
            s=s->next;
        }
        a(f);
        return ans;
    }
};

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if not head:
            return True
        f=head
        s=head
        while f.next and f.next.next:
            f=f.next.next
            s=s.next
        a=self.reverse(s)
        b=a
        ans=True
        while head and a:
            if head.val!=a.val:
                ans=False
            head=head.next
            a=a.next
        self.reverse(b)
        return ans
    def reverse(self,head):
        pre=None
        c=head
        while c:
            n=c.next
            c.next=pre
            pre=c 
            c=n
        return pre



相关文章:

  • 代码规范之Variable Names变量名
  • 如何使用 CSS 实现多列布局,有哪些注意事项
  • 一款可查看手机详细配置信息的小工具,简单直观,自动识别硬件信息
  • 创建一个服务器启动自动执行的脚本,设置默认路由
  • LUMOS: Language-Conditioned Imitation Learning with World Models
  • QT三 自定义控件,自定义控件的事件处理自定义事件过滤,原始事件过滤
  • 爬虫——将数据保存到MongoDB中
  • conda极速上手记录
  • 如何部署自己的本地大模型
  • Hadoop三 分布式sql计算hive入门
  • 基于PyTorch的艺术风格迁移系统:卷积神经网络与迁移学习在图像生成的应用
  • 【Node.js入门教程:从零到精通】
  • 关于优麒麟ukylin如何更换清华源以及ubuntu24.04安装gcc-i686-linux-gnu找不到包的问题
  • AI视频生成技术的革新之路:Video-T1项目的深度解析
  • 计算机期刊推荐 | 计算机-人工智能、信息系统、理论和算法、软件工程、网络系统、图形学和多媒体, 工程技术-制造, 数学-数学跨学科应用
  • 深度分页优化思路
  • 数据可视化TensorboardX和tensorBoard安装及使用
  • Mybatis配置文件解析(详细)
  • 设计模式,创建型设计模式,工厂模式,建造者模式,单例模式
  • UE5新材质系统效果Demo展示
  • 先去上海后赴北京,苏中城市泰州为何接连拥抱顶流“大城”?
  • 中央网信办:重点整治违规AI产品、利用AI制作发布谣言等突出问题
  • 神十九飞船已撤离空间站,计划于今日中午返回东风着陆场
  • 辽宁辽阳市白塔区一饭店发生火灾,事故已造成22人遇难3人受伤
  • 王毅:携手做世界和平与发展事业的中流砥柱
  • 流浪猫给车主造成困扰,长春一小区拟投药应对?律师:此举欠妥