234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
- 首先定义快指针和慢指针,找到中间节点。
- 然后将中间节点和尾节点之间的节点进行翻转。
- 判断是否为回文节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
ListNode* slow=head;
ListNode* fast=head;
while(fast!=NULL&&fast->next!=NULL)//找到中间节点
{
fast=fast->next->next;
slow=slow->next;
}
if(fast==NULL)//说明节点数为偶数
slow=reverseList(slow);
else
slow=reverseList(slow->next);
while(slow!=NULL)
{
if(slow->val!=head->val)
return false;
slow=slow->next;
head=head->next;
}
return true;
}
ListNode* reverseList(ListNode* head)
{
if(head==NULL||head->next==NULL)
return head;
ListNode* node=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return node;
}
};