回文结构相当于对称,所以要找到中间的那个点,这就用到了找链表中间点的方法(利用快慢指针的方法),不知道的可以去看看我之前发的博客。
struct ListNode* fast=head ,*slow=head;
while ((fast != NULL) && (fast->next != NULL))
{
fast = fast->next->next;
slow = slow->next;
}
struct ListNode* mid=slow;
重新创建的变量mid就是链表中间结点
接下来就是要将mid之后的链表翻转过来:注意前面一个3对应的那个结点中next存放的是后一个3的地址,且后面一直没有改变
翻转链表的步骤之前也发过了,这里就不过多赘述了
tail = mid;
tail = tail->next;
struct ListNode* head2 = NULL; //head2,mid,tail相当于连续的三个结点
while (mid != NULL)
{
mid->next = head2;
head2 = mid;
mid = tail;
if (tail != NULL)
tail = tail->next;
}
将链表翻转之后就变成这样了
接下来一一对应head1和head2所对应的值就好了
来看看具体代码:
bool isPalindrome(ListNode* head) {
if (head == NULL) return false;
struct ListNode* fast = head, * slow = head, * head1 = head, * tail = head;
while ((fast != NULL) && (fast->next != NULL))
{
fast = fast->next->next;
slow = slow->next;
}
struct ListNode* mid = slow;
tail = mid;
tail = tail->next;
struct ListNode* head2 = NULL;//head2,mid,tail为三个连续的结点
while (mid != NULL)
{
mid->next = head2;
head2 = mid;
mid = tail;
if (tail != NULL)
tail = tail->next;
}
while (head2 != NULL && head1 != NULL)
{
if (head2->val != head1->val)
{
return false;
}
head2 = head2->next;
head1 = head1->next;
}
return true;
}