简体   繁体   English

使用链接列表排序插入

[英]Sorted insert using Linked List

I have some difficulties to implement one iterative function for sorted insert in linked list. 我在链表中​​为排序插入实现一个迭代函数时遇到一些困难。 I have previously done that with recursion which is much easier when the insert() function is called, but here I am a bit confused with how to implement the (l->data < data) condition: 我以前用递归做了这个,这在调用insert()函数时要容易得多,但在这里我对如何实现(l->data < data)条件有点困惑:

typedef struct E_Type * List;

struct E_Type
{
  int data;
  struct E_Type* next;
};

and the function: 和功能:

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;
  }
}

I won't code this up for you, but will offer some hints. 我不会为你编写代码,但会提供一些提示。

Fundamentally, there are two cases: 从根本上说,有两种情况:

  1. The element being inserted becomes the new head. 插入的元素成为新头。 In this case, you need to update l . 在这种情况下,您需要更新l
  2. The element being inserted does not become the new head. 插入的元素不会成为新头。 In this case you need a loop. 在这种情况下,您需要一个循环。

If I were you, I'd work through both cases using pen and paper first. 如果我是你,我会首先使用笔和纸来处理这两种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM