Finding the middle point of a Linked list is a very common method. My question is why the following write-up reports an error (Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)).
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
However, I was able to pass with both writes. My question is, what is the reason for this?
ListNode* fast = head->next;
ListNode* slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
And
ListNode* fast = head;
ListNode* slow = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
Here is an example of what I wrote.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
ListNode* right = slow->next;
slow->next = nullptr;
return merge(sortList(head), sortList(right));
}
void printList(ListNode* head){
if(!head) return;
std::cout << head->val << std::endl;
printList(head->next);
}
private:
ListNode* merge(ListNode* l1, ListNode* l2){
ListNode dummy(0);
ListNode* tail = &dummy;
while(l1 && l2){
if(l1->val > l2->val){
std::swap(l1, l2);
}
tail->next = l1;
l1 = l1->next;
tail = tail->next;
}
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return dummy.next;
}
};
int main() {
Solution obj;
std::vector<int> sample = {4,2,1,3};
ListNode dummy(0);
ListNode* head = &dummy;
for(int i = 0; i < sample.size(); i++){
head->next = new ListNode(sample[i]);
head = head->next;
}
ListNode* ret = obj.sortList(dummy.next);
obj.printList(ret);
}
After a couple of iterations head
is pointing to 4
with head->next
pointing to 2
and head->next->next
being null. After your loop right
is null, slow
is pointing to 2
, you then set slow->next
to null (which it already is) and therefore pass an unmodified head
to the recursive call to sortList
. This results in infinite recursion and a stack overflow.
Your change simply prevents this situation occurring.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.