当前位置:网站首页>leetcode234题-简单方法判断回文链表
leetcode234题-简单方法判断回文链表
2022-07-27 14:36:00 【瘦皮猴117】
目录
题目
给你一个单链表的头节点
head,请你判断该链表是否为回文链表。如果是,返回true;否则,返回false。
提示:
链表中节点数目在范围 [1,105] 内,0<= Node.val <= 9
要求:时间复杂度:O(n)
空间复杂度:O(1)
分析
要满足复杂度的要求,我们可以反转从中间节点开始的子链表,将子链表与原链表对比,判断是否为回文链表。(此时并没有开辟新的链表节点,都是在原链表基础上操作的)
第一步:找出链表的中间结点
//找出中间点 public ListNode middleNode(ListNode head) { ListNode f = head; ListNode l = head; while (f != null && f.next != null) { f = f.next.next; l = l.next; } return l; }
第二步:反转从中间结点开始的子链表
//反转 public ListNode reverList(ListNode head) { if(head ==null||head.next ==null){ return head; } ListNode prev = null; ListNode cur = head; while(cur !=null){ ListNode next = cur.next; cur.next = prev;//断线 prev = cur; cur = next; } return prev; }第三步:对比原链表与子链表的值
遍历对比原链表与子链表
//遍历对比 public boolean isPalindrome(ListNode head) { ListNode midHead = middleNode(head); ListNode newHead = reverList(midHead); while (newHead != null) { if (head.val != newHead.val) { return false; } newHead = newHead.next; head = head.next; } return true; }
代码实现
三步方法结合解出题目答案
class Solution { //遍历对比 public boolean isPalindrome(ListNode head) { ListNode midHead = middleNode(head); ListNode newHead = reverList(midHead); while (newHead != null) { if (head.val != newHead.val) { return false; } newHead = newHead.next; head = head.next; } return true; } //反转 public ListNode reverList(ListNode head) { if(head ==null||head.next ==null){ return head; } ListNode prev = null; ListNode cur = head; while(cur !=null){ ListNode next = cur.next; cur.next = prev;//断线 prev = cur; cur = next; } return prev; } //中间点 public ListNode middleNode(ListNode head) { ListNode f = head; ListNode l = head; while (f != null && f.next != null) { f = f.next.next; l = l.next; } return l; } }
时间复杂度:O(n)。
空间复杂度:O(1)。
边栏推荐
猜你喜欢

C语言:三子棋游戏

后台返回来的是这种数据,是什么格式啊

Hyperlink parsing in MD: parsing `this$ Set() `, ` $` should be preceded by a space or escape character`\`

实体类(VO,DO,DTO)的划分

C语言:字符串函数与内存函数

面试重点——传输层的TCP协议

What format is this data returned from the background

【剑指offer】面试题46:把数字翻译成字符串——动态规划

Causes and solutions of deadlock in threads

Division of entity classes (VO, do, dto)
随机推荐
C语言:函数栈帧
Binder initialization process
Static关键字的三种用法
It is said that the US government will issue sales licenses to Huawei to some US enterprises!
[系统编程] 进程,线程问题总结
C语言:三子棋游戏
【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
直接插入排序
Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化
Text batch replacement function
初识MySQL数据库
C:什么是函数中的返回值(转)
Complexity analysis
Spark RPC
后台返回来的是这种数据,是什么格式啊
/Dev/loop1 takes up 100% of the problem
Insert sort directly
Spark 3.0 DPP implementation logic
Under the ban, the Countermeasures of security giants Haikang and Dahua!
Interview focus - TCP protocol of transport layer


