在链表中插入节点

时间:2018-02-17 23:56:10

标签: c algorithm struct linked-list doubly-linked-list

我试图在两个包含Node类型结构的索引之间动态插入节点。数组中的第一个元素是head指针,第二个元素是tail。

我试图在数组的两个索引之间动态增长双链表。以下是我迄今为止尝试过的代码。

我可以动态地创建头部和尾部作为节点,但根据我要求,我可以这样做。

保证在dataqllentry[0].data的值之间插入qllentry[1].data值的节点

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct Node {
    int data;
    struct Node *qprev;
    struct Node *qnext;
}Node;

struct Node qllentry[2];


int main()
{

struct Node head, tail;
    head.data = INT_MAX;
    tail.data = INT_MIN;

    head.qnext = &tail;
    tail.qprev = &head;
    head.qprev = NULL;
    tail.qnext = NULL;


    qllentry[0] = head;
    qllentry[1] = tail;
    int key = 20;
    struct Node *curr ;
    struct Node *prev;
    curr= &qllentry[0];

    while(curr->qnext != NULL && curr->data >= key) {
                curr = curr->qnext;
        }
    prev = curr->qprev;

    struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
        new_node->data = key;
        new_node->qnext = prev->qnext;
        prev->qnext = new_node;
        new_node->qprev = prev;
        if (new_node->qnext != NULL)
            new_node->qnext->qprev = new_node;


    return 0;
}

新节点的插入不会像预期的那样在头部和尾部索引之间发生。我添加了一些用于调试的打印语句

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

虽然保持一个指向列表头部和尾部的数组(或指针)没有任何问题,但是如果使用数组,则在分配地址后保持数组引用不在您的列表操作。将&array[x]与列表操作混合在一起会导致混淆。使用列表时,将其视为列表并忘记数组。

您的主要问题是迭代一个节点到远处寻找插入new_node的位置,导致您在停止之前迭代到tail。在>插入new_node之前停止节点上的迭代。您可以通过测试:

来完成此操作
    /* test curr->qnext->data > key to stop before tail */
    while (curr->qnext && curr->qnext->data > key)
                curr = curr->qnext;

注意:使用prev = curr->qprev;旁边的变量屏蔽间接级别只是隐藏详细信息 - 这可能会在以后增加混乱。它完全合法,但谨慎使用......)

现在,您可以集中精力在new_node&head之间插入&tail

在任何列表插入中,您只需重新布线当前节点的下一个指针 - >;指向下一个new_node和指针 - &gt;上一个节点指向new_node。要完成插入,new_node->qprev指向currnew_node->qnext指向curr->next,例如

    new_node->qprev = curr;         /* rewire pointers */
    new_node->qnext = curr->qnext;
    curr->qnext->qprev = new_node;
    curr->qnext = new_node;

注意:简单的解决方法是拉一张纸和一支2号铅笔并画一块 curr 一块new_node以及 tail 的块,然后为prev / next指针绘制线条(对于没有new_node的列表和使用它的列表)。然后,逻辑直线,坐到键盘上啄它。)

此外,您必须始终验证您的分配,例如

    /* allocate and VALIDATE! */
    if (!(new_node = malloc (sizeof *new_node))) {
        perror ("malloc - new_node");
        exit (EXIT_FAILURE);
    }

在你编写的动态分配内存的任何代码中,你有2个职责关于任何分配的内存块:(1)总是保留一个指向起始地址的指针因此,(2)当不再需要时,它可以释放。因此,如果您分配它,请在完成后跟踪指向块的指针和free。例如,当完成输出列表值(或在专用循环中)时,您可以释放您分配的内存,类似于:

    curr = &head;                   /* output list */
    while (curr) {
        printf ("%d\n", curr->data);
        struct Node *victim = curr; /* self-explanatory */
        curr = curr->qnext;
        /* do not forget to free allocated memory */
        if (victim != &head && victim != &tail) {
            free (victim);
        }
    }

完全放弃,您可以执行以下操作:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct Node {
    int data;
    struct Node *qprev;
    struct Node *qnext;
} Node;

struct Node qllentry[2];


int main (void) {

    struct Node head = { .data = INT_MAX }, 
                tail = { .data = INT_MIN },
                *curr,
                *new_node;

    qllentry[0] = head;     /* keep your array and list operations separate */
    qllentry[1] = tail;

    head.qnext = &tail;     /* begin list operations */
    tail.qprev = &head;

    int key = 20;

    curr = &head;

    /* test curr->qnext->data > key to stop before tail */
    while (curr->qnext && curr->qnext->data > key)
                curr = curr->qnext;

    /* allocate and VALIDATE! */
    if (!(new_node = malloc (sizeof *new_node))) {
        perror ("malloc - new_node");
        exit (EXIT_FAILURE);
    }

    new_node->data = key;           /* assign value to new_node */

    new_node->qprev = curr;         /* rewire pointers */
    new_node->qnext = curr->qnext;
    curr->qnext->qprev = new_node;
    curr->qnext = new_node;

    curr = &head;                   /* output list */
    while (curr) {
        printf ("%d\n", curr->data);
        struct Node *victim = curr; /* self-explanatory */
        curr = curr->qnext;
        /* do not forget to free allocated memory */
        if (victim != &head && victim != &tail) {
            free (victim);
        }
    }

    return 0;
}

示例使用/输出

$ ./bin/llarray
2147483647
20
-2147483648

内存使用/错误检查

必须使用内存错误检查程序,以确保您不会尝试访问内存或写入超出/超出已分配块的范围,尝试读取或基于未初始化值的条件跳转,最后,确认您释放了所有已分配的内存。

对于Linux valgrind是正常的选择。每个平台都有类似的记忆检查器。它们都很简单易用,只需通过它运行程序即可。

$ valgrind ./bin/llarray
==8665== Memcheck, a memory error detector
==8665== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8665== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==8665== Command: ./bin/llarray
==8665==
2147483647
20
-2147483648
==8665==
==8665== HEAP SUMMARY:
==8665==     in use at exit: 0 bytes in 0 blocks
==8665==   total heap usage: 1 allocs, 1 frees, 24 bytes allocated
==8665==
==8665== All heap blocks were freed -- no leaks are possible
==8665==
==8665== For counts of detected and suppressed errors, rerun with: -v
==8665== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

始终确认已释放已分配的所有内存并且没有内存错误。

简单指针转储/检查

最后,除了使用调试器踩过地址之外,您总是可以编写一个简短的调试路由来帮助您选择是否以及在哪里,您的指针处理有任何问题。 (你根本不需要输出任何东西,如果你愿意的话,你可以用相等的方式检查地址)这可以让你一次查看所有指针。只需输出节点指针的简单路由通常很有帮助。你所需要的只是,例如

void debugptrs (struct Node *list)
{
    printf ("list pointers:\n\n");
    for (struct Node *iter = list; iter; iter = iter->qnext)
        printf ("prev: %16p    curr: %16p    next: %16p\n", 
                (void*)iter->qprev, (void*)iter, (void*)iter->qnext);
    putchar ('\n');
}

哪个输出类似于:

$ ./bin/llarray
list pointers:

prev:            (nil)    curr:   0x7ffd56371910    next:        0x1038010
prev:   0x7ffd56371910    curr:        0x1038010    next:   0x7ffd56371930
prev:        0x1038010    curr:   0x7ffd56371930    next:            (nil)

我总是发现从头到尾可视地遍历地址很有帮助。如果某个节点的上一个或下一个节点不是前一行(或下一行)上该节点的地址输出,那么您就知道问题所在。

仔细看看,如果您有其他问题,请告诉我。

答案 1 :(得分:1)

以下是根据问题代码进行一些修改的代码,它按预期打印结果我猜:

<强> dlink.c:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct Node {
    int data;
    struct Node *qprev;
    struct Node *qnext;
} Snode;

int main() {
    struct Node *head = (struct Node*)malloc(sizeof(struct Node));
    struct Node *tail = (struct Node*)malloc(sizeof(struct Node));

    // init head,
    head->data = INT_MAX;
    head->qnext = tail;
    head->qprev = NULL;

    // init tail,
    tail->data = INT_MIN;
    tail->qprev = head;
    tail->qnext = NULL;

    int key = 20;
    struct Node *curr = head;
    struct Node *prev;

    //get the pointer of the process which has less priority than the current process
    while(curr->data >= key && curr->qnext != NULL) {
        curr = curr->qnext;
    }
    prev = curr->qprev;

    printf("head %p, data is %d, next is %p, prev is %p\n", head, head->data, (void *)head->qnext, (void *)head->qprev);
    printf("tail %p, data is %d, next is %p, prev is %p\n", tail, tail->data, (void *)tail->qnext, (void *)tail->qprev);
    printf("prev of new node %p, data is %d, next is %p, prev is %p\n", prev, prev->data, (void *)prev->qnext, (void *) prev->qprev);
    printf("--------------------\n\n");

    struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = key;
    new_node->qnext = prev->qnext;
    prev->qnext = new_node;
    new_node->qprev = prev;

    if (new_node->qnext != NULL)
        new_node->qnext->qprev = new_node;
    else
        tail = new_node;

    printf("head %p, data is %d, next is %p, prev is %p\n", head, head->data, (void *)head->qnext, (void *)head->qprev);
    printf("new_node %p, data is %d, next is %p, prev is %p\n", new_node, new_node->data, (void *)new_node->qnext, (void *)new_node->qprev);
    printf("tail %p, data is %d, next is %p, prev is %p\n", tail, tail->data, (void *)tail->qnext, (void *)tail->qprev);

    return 0;
}

运行结果:

head 0x2380010, data is 2147483647, next is 0x2380030, prev is (nil)
tail 0x2380030, data is -2147483648, next is (nil), prev is 0x2380010
prev of new node 0x2380010, data is 2147483647, next is 0x2380030, prev is (nil) // this is same as head,
--------------------

head 0x2380010, data is 2147483647, next is 0x2380460, prev is (nil)
new_node 0x2380460, data is 20, next is 0x2380030, prev is 0x2380010
tail 0x2380030, data is -2147483648, next is (nil), prev is 0x2380460

<强>建议

  • 不要混合struct(head,tail)&amp;结构指针(new_node),令人困惑,容易犯错。
  • 单个链表可能足以进行此类插入,在单个链表中插入元素有一种棘手的方法。
  • 要获得良好的性能,您可以分配一个大缓存,然后从缓存中创建新节点。
  • 编译c代码时,添加-Wall个选项,这会给你更多警告。