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?
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question
思路:判断一个链表含有的数值是不是一个回文的链表。可以使用快慢指针,找到一个链表的中间节点。将后半部分的链表进行逆序。而后再从head开始进行遍历,一一比对前后两部分的val值是不是相等的。当循环跳出的时候,如果遍历的指针为NULL,则说明整个链表是回文的,否则的话则说明在遍历的过程中遇到了前面部分的val和后面的val不一样的情况,则此时链表不是回文的。
/**
* 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,*fast=head->next;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
//slow后面的位置为链表的后半个部分
fast=slow->next;
slow->next=NULL;
slow=head;
ListNode *pre=NULL;
while(fast)
{
ListNode *tmp=fast->next;
fast->next=pre;
pre=fast;
fast=tmp;
}
while(pre&&slow&&pre->val==slow->val)
{
pre=pre->next;
slow=slow->next;
}
return pre?false:true;
}
};