1.题目
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
先用快慢指针找到链表的中间节点,在用头插法逆转后半部分元素,在比较。
class Solution
{
public:
bool isPalindrome(ListNode* head)
{
//将后半部分用头插法进行反转 ,然后遍历前部分和后半部分是否一致//时间 O(N),空间 O(1)
if(head == NULL ||head->next ==NULL)return true;
//快慢指针记录中间节点
auto fast=head;
auto slow=head;//遍历出中间节点
while(fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
auto p=slow->next;
ListNode* cur;
//头插法
while(p->next)
{
cur=p->next;
p->next=cur->next;
cur->next = slow->next;
slow->next=cur;
}
auto left = head;
auto right=slow->next;
//遍历前部分和后半部分是否一致
while(left &&right)
{
if(left->val != right->val)return false;
left=left->next;
right=right->next;
}
return true;
}
};