一、题目
二、思路
由于单链表无法倒着遍历,所以无法使用双指针技巧。
此题可以看做是反转链表 和 链表中间结点 的结合。定义快慢两个指针,寻找中间结点,同时在慢指针移动的过程中反转前半部分子链表。当找到中间结点时,再分别向前向后比较前后两个子链表的每一个结点值是否相同。
三、代码实现
bool isPalindrome(struct ListNode* head)
{
if(head == NULL || head->next == NULL)
{
return true;
}
struct ListNode* fast = head;
struct ListNode* slow = head; //定义两个指针找到链表中点
while(fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
//fast指针如果指向空则说明链表是偶数,slow指针还需要再向前一步
if(fast != NULL)
{
slow = slow->next;
}
//反转链表
struct ListNode* pre = NULL;
struct ListNode* cur = slow;
while (cur != NULL)
{
struct ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
while(pre)
{
if(pre->val != head->val)
return false;
pre = pre->next;
head = head->next;
}
return true;
}