为什么我对指针>next == NULL 的检查在我的链表中出现错误?

Why is my check for pointer->next == NULL coming up false in my linked list?

本文关键字:链表 我的 错误 检查 NULL 指针 gt 为什么 next      更新时间:2023-10-16

第一次将当前->下一个值设置为null时插入链表。在打印过程中,我用它来检查我是否在列表的末尾。当我在调试器中检查它时,它显示一个空值,但我的if语句[if(current->next == null)]并不能阻止无限打印。我的代码如下:

#include "List.h"
#include <cstdlib>
List::List(){
    //precondition:none
    //postcondition:empty list;position @ 1
    head = NULL;
    current = NULL;
    previous = NULL;
position = 1;
}
List::~List(){
    //precondition:link exists
    //List is now an empty linked list
makeEmpty();
}
void List::goToNext(){
    if(!isAtEnd()){
        if(current->next == NULL){
            previous == current;
            current == NULL;
        }
        else{
            previous = current;
            current = current->next;
            position +=1;
        }
    }
}
void List::goToStart(){
    if(position = 1){
        return;
    }
    else{
        current = head;
        previous = NULL;
        position = 1;
    }
}
void List::makeEmpty(){
    if(!isEmpty()){
        this->goToStart();
        while(isAtEnd() == false)
        {
            goToNext();
            delete previous;
            previous = current;
        }
        head = NULL;
        previous = NULL;
        current = NULL;
        position = 1;
    }
}
bool List::isEmpty(){
    if(this->head == NULL && this->current == NULL && this->previous == NULL){
        return true;
    }
}
bool List::isAtEnd(){
    if(current == NULL){
        return true;
    }
    else{
        return false;
    }
}
ItemType List::CurrentItem(){
    if(isAtEnd() != true){
        return current->data;
    }
}
void List::insert(ItemType item){
    nodeType * temp = new nodeType;
    temp->data = item;
    if(head == NULL){
        temp->next = NULL;
        head = temp;
        current = head;
        current->next = NULL;
    }
    else if(position == 1){
        head = temp;
        head->next = current;
        current = head;
    }
    else if(!isAtEnd() && current->next == NULL){
        temp->next = current;
        current = temp;
        if(previous != NULL){
            previous->next = current;
        }
    }
    else{
        current = temp;
        current->next = NULL;
    }
}
void List::deleteCurrentItem(){
    previous->next = current->next;
    delete current;
    current = previous->next;
    position -= 1;
}
int List::currentPosition(){
    return position;
}
////////---print function from main---///////
void print(List & testList){
    int storedPosition = testList.currentPosition();
    testList.goToStart();
    while (!testList.isAtEnd())
    {
        cout << testList.CurrentItem() << endl;
        testList.goToNext();
    }
    testList.goToStart();
    for ( int i = 1; i < storedPosition; i++)
        testList.goToNext();        
}

List::goToNext()中,您希望在设置previouscurrent时使用赋值,而不是使用比较器。

    previous = current;
    current = NULL;