02.06. 回文链表
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路:
找到链表的中位数,链表节点为偶数个找其下中位数。
逆置其后半部分链表。

遍历两个链表。比较head指针和中位数指针指向的值。如果不相等说明不是回文,返回false。
遍历结束返回true。

代码示例:
//逆置链表
struct ListNode* reverse(struct ListNode* head)
{
if (head == NULL)
return NULL;
struct ListNode* n1 = NULL, * n2 = head, * n3 = head->next;
while (n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3)
n3 = n3->next;
}
return n1;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* fast = head;
struct ListNode* slow = head;
//找到中位数
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
//逆置链表下半部分。
slow = reverse(slow);
//遍历比较每个节点。如果不相同返回false。
while (slow && head)
{
if (slow->val != head->val)
return false;
slow = slow->next;
head = head->next;
}
//相同返回true。
return true;
}
该博客介绍了如何检查一个链表是否为回文。通过找到链表中位数,然后逆置后半部分链表,最后对比原链表和逆置后的链表节点值来判断。示例代码展示了具体的实现过程,包括链表的逆置和回文检查。
239

被折叠的 条评论
为什么被折叠?



