ઇଓ 欢迎来阅读子豪的博客(LeetCode刷题篇)
☾ ⋆有什么宝贵的意见或建议可以在留言区留言
ღღ欢迎 素质三连 点赞 关注 收藏
❣ฅ码云仓库:补集王子 (YZH_skr) - Gitee.com
234. 回文链表 - 力扣(LeetCode)https://leetcode.cn/problems/palindrome-linked-list/
目录
找中间结点 然后逆置
最后一个指针判断奇偶结点
奇数个结点
偶数个结点
让mid(中间结点指向中间偏后一个)
快慢指针,获取到中间节点(slow)
从中间节点开始翻转后一半链表
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;
}
比较
代码
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,奇偶个结点
总之还是要多画图,现实中多画图,才有思路