链表的回文判断

思路:

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

代码:

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;
}
相关推荐
静听山水4 分钟前
Redis核心数据结构
数据结构·数据库·redis
im_AMBER14 分钟前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
数智工坊16 分钟前
【数据结构-树与二叉树】4.7 哈夫曼树
数据结构
!!!!81320 分钟前
蓝桥备赛Day1
数据结构·算法
七点半77020 分钟前
linux应用编程部分
数据结构
静听山水24 分钟前
Redis核心数据结构-Hash
数据结构·redis·哈希算法
zhim0033 分钟前
数据结构笔记(上)(看这亿点就够了)
数据结构
only-qi39 分钟前
leetcode24两两交换链表中的节点 快慢指针实现
数据结构·算法·链表
sin_hielo43 分钟前
leetcode 110
数据结构·算法·leetcode
执着2591 小时前
力扣hot100 - 199、二叉树的右视图
数据结构·算法·leetcode