第一次将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();
}
答案 0 :(得分:3)
在List::goToNext()
中,您希望在设置previous
和current
时使用分配,而不是使用比较器。
previous = current;
current = NULL;