您的位置:首页 > 其它

Leetcode-234. Palindrome Linked List(判断链表是否回文)

2016-06-03 10:43 471 查看
要求使用O(n)的时间复杂度和O(1)的空间复杂度

class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *fast=head,*slow=head,*aux=NULL,*temp;
while(fast&&fast->next){
temp=slow;
fast=fast->next->next;
slow=slow->next;
temp->next=aux;
aux=temp;

}
if(fast) {slow=slow->next;}
while(slow){
if(aux->val!=slow->val) return false;
slow=slow->next;
aux=aux->next;
}
return true;
}
};

这里使用fast指针每次走两步,slow每次走一步。aux逆序记录slow走过的节点。

当fast走到终点,slow走过一半,再把链表slow和aux做比较。

其中有一点要注意slow=slow->next必须在temp->next=aux之前,具体原因可画图理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表回文