我从星期天开始就一直在使用这个迭代函数,但没有成功,我想为排序插入创建迭代函数,但是在绘制节点图一小时后,我想我需要一些关于这个函数的帮助:
结构声明:
typedef struct E_Type * List;
struct E_Type
{
int data;
struct E_Type* next;
};
函数:
bool insert(List & l, int data) {
while (l != 0) {
for (List p = l; p; p = p->next) {
if (p->data == data)
return false;
}
if (l->data > data) {
List new_list = new E_Type;
new_list->data = data;
new_list->next = l;
l = new_list;
return true;
} else if (l->data < data) {
List new_list = new E_Type;
new_list->data = data;
l->next = new_list;
l = new_list;
return true;
}
}
if (l == 0) {
List new_list = new E_Type;
new_list->data = data;
new_list->next = l;
l = new_list;
return true;
}
}
顺便说一句:这个函数是否可能...所有关于此插入的教程、信息等都带有对下一个数据的递归调用
最佳答案
有很多错误:
l->next = new_list;
此行删除指针 l->next
的先前值。
没有代码可以在之前或之后寻找合适的元素来插入新元素。
你的 while 没有意义,因为你的 l
指针不会在迭代之间改变。
您最好只在纸上写下您的函数应该执行的基本步骤,然后再用 C++ 编写代码。
(或者只使用来自邻居答案的工作样本;-))
关于c++ - 排序后插入链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824619/