我编写了以下代码,以便在链接列表中插入一个整数,但是在排序方法中。
我评论了我的问题所在,并在下面解释:
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}??!
*/
}
}
答案 0 :(得分:0)
您需要记住之后插入的节点,并让该节点链接到新节点。
例如,在你的循环中找到temp
之后的节点current
,在{{prev
之前有另一个变量,比如pre = current
,然后执行current = current->next
1}}。
答案 1 :(得分:0)
{=PERCENTILE.INC(IF($B$2:$B$32=1,$A$2:$A$32,IF($B$2:$B$32=2,$A$2:$A$32,IF($B$2:$B$32=3,$A$2:$A$32,""))),0.05)}
答案 2 :(得分:0)
插入时需要一个新节点 我想只需在你想要插入的前一个节点之后创建一个新节点,比如评论中的5
答案 3 :(得分:0)
这是最终结果:(它有效!) 它处理以下情况:
void LLL::insertSorted(int r) {
node * temp = NULL;
node * current = NULL;
node * previous = NULL;
if (head == NULL) {
head = new node;
head->data = r;
head->next = NULL;
} else {
temp = new node;
temp->data = r;
temp->next = NULL;
current = head;
if (temp->data < current->data) {
temp->next = head;
head = temp;
} else {
while (current != NULL && temp->data >= current->data) {
previous = current;
current = current->next;
}
temp->next = current;
previous->next = temp;
}
}
}
&#13;