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

高效判断回文链表的3种解法

LeetCode234

给你一个单链表的头节点head,请你判断该链表是否为回文链表。如果是,返回true;否则,返回false。(回文序列是向前和向后读都相同的序列。)

Python解法

1.变成数组

# 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: res = [] current = head while current is not None: res.append(current.val) current = current.next return res == res[::-1]

2.快慢指针

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def get_mid(self, head): slow = head fast = head while fast.next is not None and fast.next.next is not None: slow = slow.next fast = fast.next.next return slow def reverse_list(self,node): cur = node pre = None while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre def isPalindrome(self, head: Optional[ListNode]) -> bool: if not head or not head: return True mid_node = self.get_mid(head) second_half = mid_node.next reverse_second = self.reverse_list(second_half) p1 = head p2 = reverse_second flag = True while flag and p2: if p1.val != p2.val: flag = False p1 = p1.next p2 = p2.next return flag

Java解法

1.变成数组

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public boolean isPalindrome(ListNode head) { int len = 0; ListNode cur = head; while(cur != null){ len++; cur = cur.next; } int[] arr = new int[len]; cur = head; for(int i = 0; i < len; i++){ arr[i] = cur.val; cur = cur.next; } int s = 0, f = len - 1; while(s < f){ if(arr[s] != arr[f])return false; s++; f--; } return true; } }

2.快慢指针

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { // 快慢指针找前半段中点 private ListNode getMid(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } // 反转链表 private ListNode reverseList(ListNode node) { ListNode cur = node; ListNode pre = null; while (cur != null) { ListNode nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } return pre; } public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } ListNode midNode = getMid(head); ListNode secondHalf = midNode.next; ListNode revSecond = reverseList(secondHalf); ListNode p1 = head; ListNode p2 = revSecond; boolean flag = true; while (flag && p2 != null) { if (p1.val != p2.val) { flag = false; } p1 = p1.next; p2 = p2.next; } return flag; } }

C++解法

1.变成数组

/** * 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) { vector<int> res; ListNode* cur =head; while(cur != nullptr){ res.push_back(cur->val); cur = cur->next; } vector<int> rev(res.rbegin(), res.rend()); return res == rev; } };

2.快慢指针

/** * 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 { private: // 找中点 ListNode* getMid(ListNode* head) { ListNode* slow = head; ListNode* fast = head; while (fast->next != nullptr && fast->next->next != nullptr) { slow = slow->next; fast = fast->next->next; } return slow; } // 反转链表 ListNode* reverseList(ListNode* node) { ListNode* cur = node; ListNode* pre = nullptr; while (cur != nullptr) { ListNode* nxt = cur->next; cur->next = pre; pre = cur; cur = nxt; } return pre; } public: bool isPalindrome(ListNode* head) { if (head == nullptr || head->next == nullptr) { return true; } ListNode* midNode = getMid(head); ListNode* secondHalf = midNode->next; ListNode* revSecond = reverseList(secondHalf); ListNode* p1 = head; ListNode* p2 = revSecond; bool flag = true; while (flag && p2 != nullptr) { if (p1->val != p2->val) { flag = false; } p1 = p1->next; p2 = p2->next; } return flag; } };
http://www.jsqmd.com/news/1148298/

相关文章:

  • BPF安全监控:能力、配置与策略实践
  • 模型推理成本可视化:从Token消耗到预算告警的监控体系
  • 2026年选F1级耐火桥架,专业公司保障安全无忧
  • 数字 IC 求职加分项:10 节课吃透大厂必考 Verilog 全考点
  • 【SkyWalking从入门到精通】第19篇:用SkyWalking提取关键路径:找到拖慢全军的瓶颈链路
  • 鸿蒙原生 ArkTS 弹窗布局深度解析:AlertDialog 与 CustomDialog 全场景对比实战
  • From descent to touchdown 全程下降着陆 / 从再入到稳稳落地
  • 小型大语言模型舍弃68%RAG上下文,保留96%召回率并降低查询成本三分之一
  • 杰理之两路PDMMIC上传PC的参考【篇】
  • 零基础用AI建站工具做网站的极速上手教程(可照做)
  • TB9051FTG与STM32实现直流电机静音控制方案
  • System Rules:给 java.lang.System 写测试不再抓瞎
  • centos7.9版本升级ssh OpenSSH 9.8p1 源码 OpenSSL 1.1.1w 源码包以及安装升级回滚文档
  • 2007-2025年上市公司供应链长鞭效应测算数据集
  • 互联网大厂 Java 求职者面试:技术与幽默的对话
  • Nx:一套搞定 Monorepo 的构建加速方案
  • 杰理之做特殊按键只响应单击事件处理【篇】
  • wp2hugo:WordPress 到 Hugo 的迁移利器,301 Star
  • 百度网盘秒传脚本:3分钟掌握文件永久分享终极指南
  • 杰理之仅选择IIS 输出,通话mic 无声【篇】
  • Python 协程池设计模式:在 RAG 场景下复用 Embedding 请求的最佳实践
  • B站AI知识库插件:将收藏夹秒变智能知识库
  • 番茄小说本地化永久保存解决方案:fanqienovel-downloader全面指南
  • 【SkyWalking从入门到精通】第21篇:用SkyWalking排查慢服务——从蛛丝马迹到真相大白
  • DLSS Swapper:游戏性能优化的智能管家,一键解锁显卡全部潜能
  • 2026年AI大模型API中转站亲测报告 主流服务商性能与成本全维度硬核排名
  • 第27章:插件系统与 Plugin Daemon 协同样式
  • GLM 5.2 来袭:开源权重模型或致 AI 推理利润崩塌,成本最多降 50%!
  • ADP5350与PIC32MX675F256L在电源管理中的协同设计
  • Transformer 自注意力复杂度 O(n²d) 详解:从矩阵乘法到 PyTorch 源码逐行分析