判断一个链表是否为回文结构
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
输入:
{1,2,2,1}
返回值:true
说明:
1->2->2->1
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
//反转链表指针 fast-template
ListNode* reverse(ListNode* head)
{
//前序节点
ListNode* pre = NULL;
ListNode* p = head;
while (p != NULL)
{
//断开后序
ListNode* next = p->next;
//指向前序
p->next = pre;
pre = p;
p = next;
}
return pre;
}
bool isPail(ListNode* head)
{
//空链表直接为回文
if(head == NULL)
return true;
ListNode* slow = head;
ListNode* fast = head;
//双指针找中点
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
//中点处反转
slow = reverse(slow);
fast = head;
while (slow != NULL)
{
//比较判断节点值是否相等
if (slow->val != fast->val)
return false;
fast = fast->next;
slow = slow->next;
}
return true;
}
};