假设链表为[1,2,3,4,5,6,7]
那么按照141题的退出条件
while (fast && fast->next)
最后fast指向7退出循环
使用234题的退出条件
while (fast->next && fast->next->next)
仍然是fast指向7退出循环
但是在实际操作中对141题使用234的条件或者对234使用141的条件均会报错,请问为什么?
第141题代码
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
第234题代码
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *last = slow->next, *pre = head;
while (last->next) {
ListNode *tmp = last->next;
last->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}
while (slow->next) {
slow = slow->next;
if (pre->val != slow->val) return false;
pre = pre->next;
}
return true;
}
};
你没有给出代码,我找到了一个
class Solution110_1 {//设置快慢指针,翻转后一半列表
public:
ListNode *reverselist(ListNode *head)
{
ListNode *pre = NULL;
ListNode *next = NULL;
while (head!=NULL)
{
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL)
return true;
ListNode *slow = head;
ListNode *fast = head;
while (fast->next!=NULL && fast->next->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
}
slow->next = reverselist(slow->next);
slow = slow->next;
while (slow!=NULL)
{
if (slow->val != head->val)
return false;
slow = slow->next;
head = head->next;
}
return true;
}
};
循环体里
slow = slow->next;
fast = fast->next->next;
这里fast还是可以通过两个next找到最后的。
关键看你的循环体怎么写。
你调试下就知道了。