假设链表为[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;
}
};