链接列表中最后一项之后的项目是否为0

Does the item after the last item in a linked list have the value of 0?

本文关键字:之后 项目 是否 一项 列表 最后 链接      更新时间:2023-10-16

我正在为作业写快速排序算法,但我想知道我的循环是否会太早停止。循环会超越最后一个元素并停止,还是会继续读取记忆中留下的随机数?这有意义吗?

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;
            }
        }
    }
}

链接列表中最后一项之后的项目是否为0?

根据定义,最后一项之后没有项目。如果最后一项之后有一项,那么以前的项目将不是最后一个。

我想知道我的循环是否会太早停止。 while循环会超越最后一个元素

快速浏览一下,循环的所有分支do curr=curr->next,循环终端条件为 curr!=NULL,因此循环将在next为null的节点后结束。如果列表的最后一个节点的next指向null,则循环不会超越它。在最后一项之前,节点的next不能指向null,因此循环也不应太早结束。

但是,如果列表的最后一项的 next并未指向null,则循环不会在该节点上结束。

您应该验证程序的行为是您期望通过使用调试器行为的方式。