为什么在尝试将新节点插入列表时出错
Why do I get errors while trying to insert a new node to a list
我有一个声明堆栈和列表的头。我正试图将的一个节点添加到列表中,但我没能做到。有人能帮我弄清楚为什么这个功能不起作用吗?
****这两个代码都是头文件中的删除***
/* a link that contains a positive integer value*/
struct link
{
int value;
struct link *next;
};
typedef struct link link;
typedef struct
{
link *head;
} linkedList;
/* a positive-integer value stack, with no size limit */
typedef struct stack
{
int count;
int maxSize;
bool empty;
linkedList* list;
} stack;
现在我要做的是:
void add(linkedList *list, int newValue)
{
linkedList* temp = list;
while (temp->head)
{
temp->head = temp->head->next;
}
temp->head->next->value = newValue; //<---- this line is making the error
}
// add new link in the beginning of list with newValue in it
在add
中,您当前正在修改temp->head
以遍历列表。temp
是一个局部变量,但它指向真实的链表,因此当您分配给temp->head
时,它会修改列表本身的结构。
我猜你真正的意图更像是:
void add(linkedList *list, int newValue)
{
link *temp = list->head;
while (temp->next != nullptr)
temp = temp->next;
link *node = new node;
node->next = nullptr;
node->value = newValue;
temp->next = node;
}
然而,对于堆栈,在添加新项之前,您不需要(或不希望)遍历列表。
void add(linkedList *list, int newValue) {
link *node = new link;
node->next = list->head;
node->value = newValue;
list->head = node;
}
不过,和往常一样,在使用链表时要三思(如果你有任何选择的话)。至少根据我的经验,很少是一个真正有用的数据结构(尤其是在像这样存储小项目的情况下),在一个典型的64位实现中,每个节点都是一个32位int和一个64位指针,所以指针的空间是数据本身的两倍
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 预处理器:插入结构名称中的前一个行号
- 在未初始化映射的情况下,将值插入到映射的映射中
- 如何在c++中只将键插入到bimap的一侧
- 如何将结构插入到集合中并打印集合的成员
- C++json插入数组
- 通过字符串::插入插入字符时出错
- 在动态分配的二维矩阵中插入新列
- 如何在不同的列中插入随机数量的值? 查询.C++.SQlite 数据库
- 在文本文件的某些行和列上插入值
- 有效地将列/行插入到就地存储在行/列主向量的矩阵中
- 在插入后与插入插入插件后对矢量进行排序
- C ado.net无法将值null插入列中
- 散列映射快速插入但检索缓慢
- 在Cassandra中插入多列
- 如何使用 ODBC API 将数据更新插入到 NVARCHAR 列中
- 如果存在插入/删除/重新散列操作,则unordered_map复制/释放包含的对象
- 如何使用C++libpqxx API将二进制数据插入PostgreSQL BYTEA列
- c++unordered_multimap插入散列