链表的回文判断

思路:

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

代码:

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;
}
相关推荐
BK贝壳4 小时前
亿级用户签到位图选型复盘:用 bool-hybrid-array 扛冷启动打卡,也把它和 Roaring/Redis 的边界测清楚了
数据结构·python·性能优化·numpy
挖井观天13 小时前
《Java数据结构》第一讲:顺序表
数据结构
炘爚15 小时前
数据结构算法总结
数据结构·python·算法
见叶之秋16 小时前
【C++】红与黑的边界:红黑树从插入到自检
数据结构·c++·算法·面试
kiracrimson16 小时前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
CQU_JIAKE18 小时前
10.25【A】
数据结构·算法
海清河晏11119 小时前
加油站问题
数据结构·算法·leetcode
GG.WinGel20 小时前
质数数目(蓝桥杯练习题)
java·数据结构·算法·青少年编程·蓝桥杯
敲代码的苦1321 小时前
头歌 数据结构—消防资源调度
数据结构·算法
ysu_031421 小时前
【C++ 进阶之路】(二)从内联函数到类与对象:深挖内存对齐、this 指针与三大默认成员函数
开发语言·数据结构·c++·笔记·面向对象·this