您的位置:首页 > 其它

234. Palindrome Linked List

2016-05-15 13:43 267 查看
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;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: