为有序链表编写插入算法C++
Writing an Insert Algorithm for an Ordered Linked List C++
我正在为有序链表编写插入算法。我已经完成了大部分算法,但是一个while循环条件让我失望了。我认为其余部分我是正确的,但任何帮助将不胜感激,谢谢!
bool MyLinkedList::Insert(ListNode *newNode)
{
// Assume ListNode is a structure and contains the variable int key;
// Assume the function returns true if it successfully inserts the node
ListNode *back = NULL, *temp = head;
if(head == NULL) // Check for inserting first node into an empty list
{
head = newNode;
return true;
}
else
{ // Search for insert location
while((**???**) && (**???**))
{
back = temp; // Advance to next node
temp = temp -> next;
{
// Check for inserting at head of the list
if(back == NULL)
{
newNode -> next = head; // Insert at head of list
head = newNode;
return true;
}
else // Insert elsewhere in the list
{
newNode -> next = temp;
back -> next = newNode;
return true;
}
}
return false; // Should never get here
}
我假设您具有以下ListNode结构(基于您之前的评论)。
struct ListNode {
int Key;
double dataValue;
ListNode *next;
}
假设列表是根据键值排序的,while 循环条件应如下所示:
while((temp != NULL) && (temp->Key < newNode->Key))
代码的其余部分似乎同意它。
如果排序列表的比较方法与简单的键比较不同,则第二个参数需要更改。
while((**???**) && (**???**))
您需要在此处插入比较。无论ListNode
里面有什么样的数据,你都应该有办法比较其中的两个。我怀疑你有一个重载的运算符,如果它不是基元类型。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 预处理器:插入结构名称中的前一个行号
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 数组 X[n] 仅存储名称.编写算法以在数组中插入或删除 ITEM
- C++ std::向量插入两个元素替代算法失败
- 插入排序算法在放入函数时的行为不同
- 使用算法中的插入函数将元素插入空容器中,未给出预期的结果
- 使用第二个数组C 插入排序算法
- C++中的插入排序算法
- 在循环双向链表的第一个节点之前/之后插入的算法是什么?
- 为有序链表编写插入算法C++
- c++ 插入数组算法故障
- 双链表插入项算法有缺陷
- 二叉树插入算法
- 并行算法,做一个小的插入/移位
- 我是否需要知道算法的代码才能利用插入器和移动迭代器?
- 插入排序算法忽略第一个元素