C++ 如何在头部的特定节点后插入链表?c++;
我编写了以下代码来向链表中插入一个整数,但采用的是排序方法 我评论了我的问题所在,并解释如下:C++ 如何在头部的特定节点后插入链表?c++;,c++,linked-list,nodes,head,C++,Linked List,Nodes,Head,我编写了以下代码来向链表中插入一个整数,但采用的是排序方法 我评论了我的问题所在,并解释如下: void LLL::insertSorted(int r) { node * temp = NULL; node * current = NULL; if (head == NULL) { head = new node; head->data = r; head->next = NULL; } else {
void LLL::insertSorted(int r) {
node * temp = NULL;
node * current = NULL;
if (head == NULL) {
head = new node;
head->data = r;
head->next = NULL;
} else {
temp = new node;
temp->data = r;
current = head;
while (temp->data > current->data && current != NULL) {
current = current->next;
}
temp->next = current;
/*
* Assume that I have head points to this list: { 3 -> 5 -> 8 -> NULL }
* And I want to insert {6} (temp) to the list just after 5; then what
* I've done so far on my previous code I made temp = {6 -> 8 -> NULL}.
* NOW!! How can correctly insert temp to ((head)) just after {5}??!
*/
}
}
您需要记住要插入的节点,并将该节点链接到新节点
例如,在查找
temp
,current
之后的节点的循环中,使用另一个变量,例如prev
,并在current=current->next
之前执行pre=current
,插入时需要一个新节点
void LLL::insertSorted(int r) {
node * cur = head;
node * prev = NULL;
while((cur != NULL) && (r > cur->data)){//find the location to insert
prev = cur;
cur = cur->next;
}
node *new_node = new node;
new_node->data = r;
new_node->next = cur;
if(prev == NULL){//new first one
head = new_node;
}else{
prev->next = new_node;
}
}
我想只需在您要插入的前一个节点之后再创建一个新节点,如注释中的5,这是最终结果:(它可以工作!)
它处理以下情况:
- 案例1:头部是空的
- 案例2:新元素是列表中最小的元素 < LI> 3:新元素在列表中间的某个地方。
- 案例4:新元素是最大的
void LLL::insertSorted(int r){
节点*temp=NULL;
节点*当前=空;
node*previous=NULL;
if(head==NULL){
头=新节点;
头部->数据=r;
head->next=NULL;
}否则{
temp=新节点;
温度->数据=r;
temp->next=NULL;
电流=水头;
如果(临时->数据<当前->数据){
温度->下一步=头部;
压头=温度;
}否则{
while(当前!=NULL&&temp->data>=当前->数据){
先前=当前;
当前=当前->下一步;
}
温度->下一步=当前;
上一个->下一个=温度;
}
}
}
你能告诉我如何准确地使用我的代码片段吗?你的意思是让前一个节点取消对{5}的引用,并使previous->next=temp?当你浏览链接时,你需要一个前一个tem,add previous=current;当前之前=当前->下一步;后温度->下一步=当前;添加上一个->下一个=临时@JerryChen我已经在我的代码片段中添加了你的建议。这就是你的意思吗?如果是的话,我将如何改变我的想法。空列表2。最小的number@JerryChen你能再解释一下吗?我不熟悉这个概念,我比wordshow更了解代码,这会改变我的想法吗?你能解释一下吗?所以你只需要在列表为空时,或者当你想插入的数字最小时,改变你的头。如果列表为空,则“new_node”为(num,empty),我们将这个新的_节点分配给head。否则(当列表不是空的,并且您尝试插入的数字是最小的),代码中的“while loop”部分将不会执行,因为num(r)while(temp->data>current->data&¤t!=NULL)
更改为while(temp->data>current->next->data&¤t!=NULL)
,这将使“6”与8比较,而不是5,并且它将插入5之后,而不是8之前,您不需要添加“previous”节点,只需添加“next”,对不起,我的英语不好。你的英语很好,但我更懂代码。因此,如果你能用我的代码来解决问题,我们不需要英语汉克,我想你可以这样尝试,而不必更改你编写的其他代码,只需这句while语句,因为你写的是“插入之前”而不是“插入之后”:下面的插入函数似乎还可以。检查Node和List的构造函数。@JerryChen如果我将循环条件的第二部分更改为(current->next!=NULL,它就会工作,但是如果我输入了{1,2,3,4,5}我得到{2,3,4,5,1},它就会跳过第一个输入!你知道有什么问题吗?以及如何修复它。(请用代码回答,用一点英语)