我第一次将 current->next 值设置为 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();
}