Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用链表排序插入_C++_Linked List_Iteration - Fatal编程技术网

C++ 使用链表排序插入

C++ 使用链表排序插入,c++,linked-list,iteration,C++,Linked List,Iteration,对于链表中的排序插入,我很难实现一个迭代函数。我之前已经使用递归实现了这一点,调用insert()函数时,递归要容易得多,但在这里,我对如何实现(l->data数据>数据){ List new_List=新的E_类型; 新建列表->数据=数据; 新建列表->下一步=l; l=新列表; } else if(l->data数据=数据; new_list->next=l;//我用这个在黑暗中拍摄 l=新列表; } } 我不会为您编写代码,但会提供一些提示 基本上有两种情况: 正在插入的图元将成为新的标

对于链表中的排序插入,我很难实现一个迭代函数。我之前已经使用递归实现了这一点,调用
insert()
函数时,递归要容易得多,但在这里,我对如何实现
(l->data
条件感到有点困惑:

typedef struct E_Type * List;

struct E_Type
{
  int data;
  struct E_Type* next;
};
以及功能:

insert(List & l, int data){
  if (l == 0 || l->data > data){
    List new_list = new E_Type;
    new_list->data = data;
    new_list->next = l;
    l = new_list;
  }
  else if (l->data < data){
    List new_list = new E_Type; 
    new_list->data = data;
    new_list->next = l; //i am shooting in the dark with this one
    l = new_list;
  }
}
insert(列表和列表,整数数据){
如果(l==0 | | l->数据>数据){
List new_List=新的E_类型;
新建列表->数据=数据;
新建列表->下一步=l;
l=新列表;
}
else if(l->data数据=数据;
new_list->next=l;//我用这个在黑暗中拍摄
l=新列表;
}
}

我不会为您编写代码,但会提供一些提示

基本上有两种情况:

  • 正在插入的图元将成为新的标头。在这种情况下,您需要更新
    l
  • 插入的元素不会成为新的头。在这种情况下,您需要一个循环

  • 如果我是你,我会先用笔和纸来处理这两种情况。

    或者使用巧妙的实现,使用一个虚拟头,从而大大简化代码。