【C语言】234.回文链表【LeetCode】

简介: 【C语言】234.回文链表【LeetCode】

ઇଓ 欢迎来阅读子豪的博客(LeetCode刷题篇)


☾ ⋆有什么宝贵的意见或建议可以在留言区留言


ღღ欢迎 素质三连 点赞 关注 收藏


❣ฅ码云仓库:补集王子 (YZH_skr) - Gitee.com

234. 回文链表 - 力扣(LeetCode)

https://leetcode.cn/problems/palindrome-linked-list/


59a4289e8ee54a4093bec406e07f7ae4.png


找中间结点 然后逆置


最后一个指针判断奇偶结点


奇数个结点


80e50d9cd4f842ccaf25427900d0df3a.png


偶数个结点


让mid(中间结点指向中间偏后一个)


663870b192c846c9be4ef0b3dfd949d4.png


快慢指针,获取到中间节点(slow)


4801e1ee285645ba8e5df3d239d93422.png


从中间节点开始翻转后一半链表


dc046d3b75774d2eb3ec6da70aa86576.png


struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* prev = NULL;
    struct ListNode* curr = head;
    while (curr) {
        struct ListNode* next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}


比较


469af6208fb3417ba75389c70dec2d72.png


代码


struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* prev = NULL;
    struct ListNode* curr = head;
    while (curr) {
        struct ListNode* next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        // 快慢指针,获取到中间节点,从中间节点开始翻转后一半链表
        struct ListNode* slow, *fast, *mid, *cur;
        slow = fast = A;
        while(fast && fast->next)
        {
            fast = fast->next->next;
            slow = slow ->next;
        }
        if(fast != NULL)
        slow = slow->next;
        mid = slow;
        cur = reverseList(mid);
        while(cur->next != NULL)
        {
            if(A->val != cur->val)
                return false;
                cur = cur->next;
                A = A->next;
        }
        return true;
    }
};


补充:侵入式编程:破坏了原来的结构


总结


本题要考虑几个因素


1,访问越界问题


2,如何比较


3,奇偶个结点


总之还是要多画图,现实中多画图,才有思路

相关文章
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
6天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
|
6天前
|
存储 算法 C语言
C语言刷题~Leetcode与牛客网简单题
C语言刷题~Leetcode与牛客网简单题
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C语言
链表的插入、删除和查询—C语言
链表的插入、删除和查询—C语言
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
6天前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)