@TOC
1. 题目
题目链接:链表的回文结构
2. 思路及小注意
这道题目整合了之前几道题目,返回链表中间节点,反转单链表。需要比较熟悉。
判断是否为回文链表 ——
:black_heart: 1. 找到中间节点
:black_heart: 2. 逆置后半个链表
:black_heart: 3. 遍历比较,确定终止条件
3. 题解
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
// 1.寻找链表的中间节点
struct ListNode* fast = A;
struct ListNode* slow = A;
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
// 2.反转链表
struct ListNode* prev = NULL;
struct ListNode* cur = slow;
struct ListNode* next = slow->next;
while(cur)
{
cur->next = prev;//反转
//迭代
prev = cur;
cur = next;
if(next)
next = next->next;
}
// 3.比较是否相同
while(A && prev)
{
if(A->val != prev->val)
{
return false;
}
A = A->next;
prev = prev->next;
}
return true;
}
};
:star: After all this time?
:black_heart: Always.
持续更新~@边通书