c++ - 排序后插入链表

标签 c++ linked-list

我从星期天开始就一直在使用这个迭代函数,但没有成功,我想为排序插入创建迭代函数,但是在绘制节点图一小时后,我想我需要一些关于这个函数的帮助:

结构声明:

  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/

相关文章:

c++ - 在 Makefile 中自动选择与 C++11 兼容的 g++ 版本

c++ - SFML 2.0 循环 Sprite 显示不止一次

c++ - GCC/LD找不到链接库

c++ - 使用 avcodec_close 的 ffmpeg 问题

java - 为集合中的每个项目创建 Swing GUI 元素 - JAVA

C、链表段错误

c++ - "std::is_callable"在 C++17 中被 "std::is_invocable"替换了吗?

java - 在 for 循环中创建和链接 LinkedList

c - 系统编程中链表的使用

c++ - 使用 libfm Linux 在 C 中自定义操作或命令?