如何在head中的特定节点后插入链表?c++
how to insert a linked list after a particular node inside head? c++
我编写了以下代码,将一个整数插入到链表中,但采用了排序方法。
我评论了我的问题所在,并在下面进行了解释:
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}??!
*/
}
}
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;
}
}
您需要记住在哪个节点之后插入,并使该节点链接到新节点。
例如,在循环中查找temp
、current
之后的节点,使用另一个变量prev
,并在current = current->next
之前执行pre = current
。
插入时需要一个新节点
我认为只需在您想要插入的上一个节点之后创建一个新节点,如注释中的5
这是最终结果:(有效!)它处理以下情况:
- 情况1:头部是空的
- 情况2:新元素是列表中最小的
- 情况3:新元素位于列表的中间位置
- 情况4:新元素是最大的
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;
}
}
}
相关文章:
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 将二叉树的节点插入链表 (C++)
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 单个链表,节点插入最低到最高节点值的问题
- 无法将节点插入C 中的链接列表中
- 将节点插入链表只会转到开头或结尾
- 将节点插入 BST
- 按排序顺序将节点插入链表
- LinkedList节点插入
- 二进制搜索树节点插入
- 使用级别顺序遍历将节点插入二叉树
- 尝试将节点插入链表中,但我需要一个重载运算符<函数
- 将节点插入二叉搜索树
- 尝试将节点插入矢量<node>,但程序在push_back时不断崩溃
- 将节点插入二进制搜索树/链表
- 将节点插入到不带头指针的排序列表中
- 错误:SList.cpp:(.text+0x69):尝试将节点插入链表头C++时未定义对"SLNode::SLNode()"的引用
- 为什么在尝试将新节点插入列表时出错
- 节点插入二进制树C++
- 为什么我不能将 head 之后的节点插入C++链表?