链表的回文判断

思路:

找中间节点-->逆置->比较

代码:

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* middleNode(struct ListNode* head)
{
struct ListNode*slow=head;
struct ListNode*flast=head;
while(flast&&flast->next)
{
    slow=slow->next;
    flast=flast->next->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head){
    struct ListNode*newhead=NULL;
    struct ListNode*cur=head;
    while(cur)
    {
        struct ListNode*per=cur->next;
        cur->next=newhead;
        newhead=cur;
        cur=per;
    }
    return newhead;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* mid=middleNode(head);//找中间节点
        struct ListNode* rmid=reverseList(mid);//逆置
        //比较
        while(head&&rmid)
        {
            if(head->val==rmid->val)
            {
                head=head->next;
                rmid=rmid->next;
            }else {
            return false;
            }
        }
        return true;
}
相关推荐
艾莉丝努力练剑2 小时前
【Linux指令 (二)】不止于入门:探索Linux系统核心与指令的深层逻辑,理解Linux系统理论核心概念与基础指令
linux·服务器·数据结构·c++·centos
C嘎嘎嵌入式开发2 小时前
(10)100天python从入门到拿捏《Python中的数据结构与自定义数据结构》
数据结构·python·算法
Vect__2 小时前
从底层到上层的“外挂”:deque、stack、queue、priority_queue 全面拆解
数据结构·c++
草莓熊Lotso2 小时前
C++ 手写 List 容器实战:从双向链表原理到完整功能落地,附源码与测试验证
开发语言·c++·链表·list
玖釉-3 小时前
三维模型数据结构与存储方式解析
数据结构·算法·图形渲染
努力努力再努力wz4 小时前
【C++进阶系列】:万字详解特殊类以及设计模式
java·linux·运维·开发语言·数据结构·c++·设计模式
青岛少儿编程-王老师14 小时前
CCF编程能力等级认证GESP—C++7级—20250927
数据结构·c++·算法
nanaki5021316 小时前
数据结构(3) ----------- 栈、队列
数据结构
一只小透明啊啊啊啊16 小时前
b树,b+树,红黑树
数据结构·b树·b+树
Mingze031416 小时前
C语言四大排序算法实战
c语言·数据结构·学习·算法·排序算法