链表的回文判断

思路:

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

代码:

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;
}
相关推荐
不知名XL3 小时前
day50 单调栈
数据结构·算法·leetcode
cpp_25015 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25015 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder1235 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵6 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi6 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_25016 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
浅念-6 小时前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
爱吃生蚝的于勒6 小时前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习
数智工坊7 小时前
【数据结构-树与二叉树】4.6 树与森林的存储-转化-遍历
数据结构