链表的回文判断

思路:

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

代码:

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;
}
相关推荐
Yang_jie_031 天前
笔记:数据结构(栈是否使用底指针以及头指针的初始化值)
数据结构·笔记·算法
lueluelue471 天前
LeetCode:滑动窗口
数据结构·算法·leetcode
码少女1 天前
数据结构——冒泡排序及优化
数据结构·算法·排序算法
青梅橘子皮1 天前
string---入门OJ题(1)
数据结构·算法
小高Baby@1 天前
单链表的删操作
数据结构·算法·golang
qq_454245031 天前
BasicMethod.Map 设计框架:8 个并行基础模块的数学根基与实现
数据结构·算法·c#
青山木1 天前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先
ysa0510301 天前
【板子】树上启发式合并
数据结构·c++·笔记·算法
2301_800256111 天前
数据结构基础期末复习例题
数据结构·算法
tachibana21 天前
hot100 将有序数组转换为二叉搜索树(108)
java·数据结构·算法·leetcode