leetcode刷题—回文链表
创始人
2025-05-29 11:58:30
0

回文链表

        • 1.题目:
        • 2.画图理解
        • 3.代码的实现

1.题目:

给定一个链表的 头节点 head ,请判断其是否为回文链表。

如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。

在这里插入图片描述
进阶:能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

2.画图理解

在这里插入图片描述

链表的中间结点和反转链表实现方法之前有写过:
链表的中间结点:https://editor.csdn.net/md/?articleId=129284874
反转链表:https://editor.csdn.net/md/?articleId=129309640

3.代码的实现


//链表的中间结点:如果有两个中间结点,则返回第二个中间结点。
struct ListNode* middleNode(struct ListNode* head){struct ListNode* slow=head,*fast=head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;}return slow;
}//反转链表
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur=head,*newhead=NULL;while(cur){struct ListNode* next=cur->next;cur->next=newhead;newhead=cur;cur=next;}return newhead;
}bool isPalindrome(struct ListNode* head){//拿到链表的中间结点struct ListNode* mid = middleNode(head);//从中间结点开始逆置struct ListNode* rhead = reverseList(mid);struct ListNode* curhead = head;struct ListNode* curRhead = rhead; //当curhead 和 curRhead任意一个为空则结束while(curhead && curRhead){//curhead 和 curRhead不相等时返回falseif(curhead->val != curRhead->val){return false;}//否则curhead 和 curRhead指向nextelse{curhead=curhead->next;curRhead=curRhead->next;}}//直到curhead 或 curRhead为空还没返回false,则返回truereturn true;
}

完结~

相关内容

热门资讯

修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
【前端】‘??‘与‘||‘有什... 0 问题 经常写const data = res.data.a ?? ''或者const d...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
牛客计算器的改良(Python... 文章目录1.题目描述2.输入描述:3.输出描述:4.示例15.分析6.代码7.结语 链接࿱...
正大杯|市调大赛|2023备赛... 关键信息 同时随着精细化养宠趋势的深入,宠物消费类目日渐丰富。 本报告通过 Niuco...
QGIS下载在线地图(Goog... 前言 国内外有很多在线地图下载软件,但功能单一,基本上只能下载数据&#x...