如何将值插入单个链接列表中
How to insert values into single linked list
我正在尝试学习一些有关单个链接列表的基础知识,因此我掌握了创建一些代码的想法。可悲的是,我给了构造函数遵循。
现在我创建了我想要的所有方法。不幸的是,我的插入似乎不起作用,所以我什至无法检查其他方法是否有效。插入方法的OFC角色是将数字添加到排序的列表l中。如果没有这样的数字,则应在第一个数字之前放在第一个数字之前,如果它更大或放在列表的末尾。
。#include <iostream>
#include <cassert>
using namespace std;
struct lnode
{
int key;
lnode* next;
lnode(int k, lnode* n=nullptr):key(k),next(n){}
};
void insert( lnode* &L, int x)
{
while(L)
{
if(x >= L->key)
{
L = L->next;
}
else
{
lnode* temp = L;
L = new lnode(x, nullptr);
L->next = temp;
break;
}
}
}
int main()
{
lnode* t = nullptr;
insert(t,3);
insert(t,4);
insert(t,1);
insert(t,7);
insert(t,-4);
insert(t,9);
insert(t,2);
while(L) {
std::cout << L->key << " ";
}
}
我期待什么?我的期望是查看列表的元素。此刻什么都没有。没有错误,没有结果。
编写简单单连锁列表修改代码的诀窍是使用指针指向指针电流节点来指示您的位置:
void insert( lnode* &L, int x)
{
lnode **pos = &L;
while (*pos && (*pos)->key <= x) {
pos = &((*pos)->next);
}
*pos = new lnode(x,*pos);
}
,由于您说的是初学者,因此也许您应该从初学者开始:
void insert( lnode* &L, int x)
{
if (!L || L->key > x) {
//insert at head
L = new lnode(x, L);
return;
}
lnode *previous=L;
lnode *current=L->next;
while(current && current->key <= x) {
previous = current;
current = current->next;
}
//insert between previous and current
previous->next = new lnode(x, current);
}
与上一个相比,显示了在搜索时使用lnode **
跟踪插入位置的好处:
- 没有特殊情况插入头部
- 没有单独的变量用于上一个和下一个
该代码应起作用。修复了编译错误以及在Matt代码顶部打印时的遍历逻辑。
#include <iostream>
#include <cassert>
using namespace std;
struct lnode
{
int key;
lnode* next;
lnode(int k, lnode* n = nullptr) :key(k), next(n) {}
};
void insert(lnode* &L, int x)
{
lnode **pos = &L;
while (*pos && (*pos)->key <= x) {
pos = &((*pos)->next);
}
*pos = new lnode(x, *pos);
}
int main()
{
lnode * t = nullptr;
insert(t, 3);
insert(t, 4);
insert(t, 1);
insert(t, 7);
insert(t, -4);
insert(t, 9);
insert(t, 2);
while (t) {
std::cout << t->key << " ";
t = t->next;
}
}
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表