我试图在链表中的给定位置添加一个节点,但由于某些原因,我陷入了无限循环。当我运行以下代码时,循环中的cout语句将永远输出。这个问题的发生是因为我做了错误的循环,还是因为我在使用指针时搞砸了?这是我第一次处理指针,我想我已经迷失了方向。
注意:我正在学习如何在给定的位置插入节点,所以下面的代码在语法上是完整的。
这是我的代码:
void LList::InsertElement(){
// PRE: the N. O. LList is valid
// POST: a new element thing has been inserted at the
// given position of the list.If that position doesn't
// exist, the LList will be unchanged.
listnode * temp;
element thing;
int position;
int inc;
inc = 1;
cout << "Enter the position where you want to add the element at: ";
position = read_position();
cout << "Enter the element value: ";
thing = read_element();
temp = new listnode;
temp -> data = thing;
if (listSize==0 && position==1){
head = temp;
temp -> next = nullptr;}
else if(position<= listSize){
temp = head;
while(inc < position){ // for some reasons this loop is infinite
temp -> next = temp;
temp = temp -> next;
cout << endl<< "NEXT: " << temp -> data;
inc +=1;
}
temp -> data = thing;
}
else;
}
好吧,这样做吧:
while(inc < position)
{
// print data
cout << endl<< "NEXT: " << temp -> data;
// increment temp to point to next
temp = temp -> next;
inc +=1;
}
您的代码是:
temp -> next = temp;
temp = temp -> next;
这条线使它一次又一次地遍历相同的数据。循环中的循环,永远运行。
感谢你们的帮助。这是我的最后一个代码,因为你们的帮助,它正在工作,谢谢。
current = head;
while(inc < position){
current = current -> next;
inc +=1;
}
temp -> next = current -> next;
current -> next = temp;