当前位置:网站首页>[C题目]力扣234. 回文链表
[C题目]力扣234. 回文链表
2022-08-02 20:33:00 【GLC8866】
思路:
struct ListNode* MiddleNode(struct ListNode* head)
{
struct ListNode* slow=head;
struct ListNode* fast=head;
while(fast&&fast->next)//防止结点为奇数个时,fast->next先为NULL,fast应该写在fast->next的左边。
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head)
{
//创建哨兵位的头结点
struct ListNode* newhead=(struct ListNode*)malloc(sizeof(struct ListNode));
newhead->next=NULL;//看作指向NULL结点
struct ListNode* cur=head;
while(cur)
{
struct ListNode* tmp=cur->next;
cur->next=newhead->next;
newhead->next=cur;
cur=tmp;
}
return newhead->next;
}
bool isPalindrome(struct ListNode* head)
{
struct ListNode* middle=MiddleNode(head);
struct ListNode* newhead=reverseList(middle);
struct ListNode* cur1=head;
struct ListNode* cur2=newhead;
while(cur2)//奇数个结点时,虽然后半段节点数比前半段结点数多一个,但当cur2指向middle时,cur1也存着middle的地址(指针域并没有被覆盖),所以cur2->val依然等于cur1->val,不影响判断两个链表是否相等。
{
if(cur2->val!=cur1->val)
return false;
cur1=cur1->next;
cur2=cur2->next;
}
return true;
}
边栏推荐
猜你喜欢
随机推荐
【SLAM】DM-VIO(ros版)安装和论文解读
数字孪生助力智慧城市可视化建设
典型相关分析CCA计算过程
实现fashion_minst服装图像分类
2170. 使数组变成交替数组的最少操作数
WPF development through practical 】 【 automatic production management platform
"A daily practice, happy water problem" 1374. Generate a string with an odd number of each character
一款免费的容器安全 SaaS 平台使用记录
C primer plus学习笔记 —— 9、联合&枚举&typdef
Wiring diagrams of switches, motors, circuit breakers, thermocouples, and meters
X 2 Earn必须依靠旁氏启动?GameFi的出路在哪?(下)
【实战 已完结】WPF开发自动化生产管理平台
信息系统项目管理师必背核心考点(五十八)变更管理的主要角色
【3D视觉】深度摄像头与3D重建
callback prototype __proto__
Xcode13.1运行工程报错fatal error: ‘IFlyMSC/IFly.h‘ file not found的问题
新增指令 v-memo
【流媒体】推流与拉流简介
包管理工具npm- node package management相关知识 、检查包更新、NPM包上传、更换镜像、npm ERR! registry error parsing json
《分布式微服务电商》专题(一)-项目简介







