
链表面试题(7)
发布日期:2021-05-11 02:22:32
浏览次数:12
分类:精选文章
本文共 2018 字,大约阅读时间需要 6 分钟。
(8)、链表的回文结构
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。 给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。 https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa?class Solution { public boolean isPalindrome(ListNode head) { if(head==null || head.next==null){ return true; } //1、找中间节点 ListNode fast=head; ListNode slow=head; while(fast!=null && fast.next!=null){ fast=fast.next.next; slow=slow.next; } //2、反转后半部分 ListNode cur=slow.next; while(cur!=null){ ListNode curNext=cur.next; cur.next=slow; slow=cur; cur=curNext; } //3、slow从后往前走,head从前往后走 while(slow != head){ if(head.val != slow.val){ return false; } if(head.next==slow){ return true; } head=head.next; slow=slow.next; } return true; }}
(9、两个链表的第一个公共结点
https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/public class Solution { public static ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode pL = headA;//永远指向长的单链表 ListNode pS = headB;//永远指向短的单链表 int lenA = 0; int lenB = 0; //求的lenA lenB while (pL != null) { lenA++; pL = pL.next; } while (pS != null) { lenB++; pS = pS.next; } pL = headA; pS = headB; //差值-》最长的单链表先走len步 int len = lenA - lenB; if (len < 0) { pL = headB; pS = headA; len = lenB - lenA; } //让pL先走len步 while (len > 0) { pL = pL.next; len--; } //开始一起走 (pL != pS )---->一人一步走 while (pL != pS) { pS = pS.next; pL = pL.next; } return pL; }}
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月27日 18时19分07秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
嘿!为你的应用创建滚动日志吧?
2021-05-09
一个JAVA应用启动缓慢问题排查 --来自jdk securerandom 的问候
2021-05-09
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
2021-05-09
httprunner学习23-加解密
2021-05-09
jenkins学习13-凭据管理(删除多余的凭据)
2021-05-09
有道云笔记 同步到我的博客园
2021-05-09
阿里云“网红"运维工程师白金:做一个平凡的圆梦人
2021-05-09
AnalyticDB for PostgreSQL 6.0 新特性介绍
2021-05-09
Alibaba Cloud Linux 2 LTS 正式发布,提供更高性能和更多保障!
2021-05-09
李笑来必读书籍整理
2021-05-09
vue书籍整理
2021-05-09
记Java中有关内存的简单认识
2021-05-09
Mybatis配置解析
2021-05-09
http头部 Expect
2021-05-09
Hadoop(十六)之使用Combiner优化MapReduce
2021-05-09
C#实现outlook自动签名
2021-05-09
《机器学习Python实现_10_06_集成学习_boosting_gbdt分类实现》
2021-05-09
CoreCLR源码探索(八) JIT的工作原理(详解篇)
2021-05-09