I am writing a quick sort algorithm for homework but I was wondering if my loop will stop too early. Will the while loop go past the last element and stop or will it keep reading random numbers that were left over in the memory? Does that make sense?
void ListP::partition(ListNode * &Larger, ListNode * &Smaller, ListNode * &pivot ){
ListNode *curr, *temps, *templ; *temps= *templ = NULL;
curr=pivot->next;
pivot->next=NUll;
while(curr!=NULL){
if (curr->item<=pivot->item){
if(Smaller==NULL){
Smaller=curr;
curr=curr->next;
Smaller->next=NULL;
temps=Smaller;
}
else{
temps->next=curr;
curr=curr->next;
temps=temps->next;
temps->next=NUll;
}
}
else{
if(Larger==NULL){
Larger=curr;
curr=curr->next;
Larger->next=NULL;
templ=Larger;
}
else{
templ->next=curr;
curr=curr->next;
templ=templ->next;
templ->next=NUll;
}
}
}
}
Does the item after the last item in a linked list have the value of 0?
By definition, there is no item after the last item. If there was an item after the last item, then the one before would not be the last.
I was wondering if my loop will stop too early. Will the while loop go past the last element
At a quick glance, all branches of the loop do curr=curr->next
, and the loop end condition is curr!=NULL
, so the loop will end after a node whose next
is null. If next
of the last node of your list points to null, then the loop shouln't go past it. next
of a node before the last item cannot point to null, so the loop shouldn't end too early either.
However, if next
of the last item of the list doesn't point to null, then the loop won't end on that node.
You should verify that the program behaves the way you expect it to behave by using a debugger.