如何将值插入单个链接列表中

How to insert values into single linked list

本文关键字:链接 列表 单个 插入      更新时间:2023-10-16

我正在尝试学习一些有关单个链接列表的基础知识,因此我掌握了创建一些代码的想法。可悲的是,我给了构造函数遵循。

现在我创建了我想要的所有方法。不幸的是,我的插入似乎不起作用,所以我什至无法检查其他方法是否有效。插入方法的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;
    }
}