根据位置从链表创建子列表?

时间:2016-10-01 19:06:58

标签: c algorithm linked-list

我试图输入一个带2个链表的函数。一个具有要打印的值,第二个具有要打印的链接列表值的位置。它给了我一个错误,我把它作为注释放在代码中。

的Structs

typedef int Item;
typedef struct node_struct * link;
typedef struct list_struct * list;

struct node_struct {
    Item item;
    link next;
};

struct list_struct {
    link first;
    int length;    
};

功能:

list sublist(list A, list pos_list) {
    link tempOne;
    link tempTwo;
    link node = malloc(sizeof *node);
    tempOne = pos_list->first;
    tempTwo = A->first;
    int counter;
    while(tempOne->next != NULL)
    {
        counter = 0;
        while(counter < tempOne->item && tempOne->next != NULL)
        {
            tempTwo = tempTwo->next;
            counter = counter+1;
        }
        node->item = tempTwo->item; //EXC_BAD_ACCESS code:1
        node = node->next;
        tempTwo = A->first;
        tempOne = tempOne->next;
        counter = 0;
    }
    return node;

1 个答案:

答案 0 :(得分:0)

代码中存在许多不良做法,这使得您和我们很难理解(并因此调试和维护)此类代码。

  • 当无意隐藏指针
  • 背后的实际数据时,您正在创建指针typdef
  • 您正在使用相同的数据类型创建位置链接列表和数据链接列表。我理解你的情况都是int,但是不要使用误导typedef int Item而只是坚持使用int
  • 在这种情况下,
  • tempOnetempTwo可能是最差的命名选项,不仅用于调用具有非直观名称的变量(如temp),还将第一个arg称为{ {1}}和第二个arg为Two - 尽可能反直觉
  • 我可以看到你使用两种不同结构的情况One(坦率地说我会称之为node_struct)和nodelist_struct评论),但在这个例子中,你不需要node_struct,它只会给代码增加更多的混淆。
  • 您应该在单独的函数中执行“查找”作业(内部list_struct),这样您就可以轻松处理错误,而不会将内部循环与外部循环混淆

除此之外,您还没有指定for loop是否实际包含相对位置(从先前位置开始的位置)或绝对位置(如数组索引)。我会假设它是绝对的位置。

执行pos_list后,您需要再次node = node->next;。或者更确切地说,在线malloc上使用它之前将它与malloc一起使用并摆脱循环中的node->item = tempTwo->item;

我没有方便的c编译器,所以无法测试它。但我没有看到任何其他问题

修改

我注意到子列表的返回值始终只是最后一个节点,而不是链表中的第一个节点 - 这显然也是一个问题。

以下是我编写此代码的方法。请记住,这不是经过调试和测试过的代码,而只是表达了这个想法(如果你愿意,可以先草拟)

malloc