0

我正在使用链接列表并尝试在 where'th 节点之后插入一个带有数据 d 的新节点。出于某种原因,我得到了不正确的结果。这是我的代码:

void insertAfter(int d, int where )  
{
    struct list * marker = head;
    struct list * new;

    while(marker -> data != where)
        marker = marker -> next;
    new = (struct list*)malloc(sizeof(struct list));

    new -> next = marker -> next; 
    marker -> next = new;
    new -> data = d; 
}
4

3 回答 3

1

我可以建议一个更安全的版本以及一些评论:

void insertAfter(int d, int where )  
{
    struct list * marker = head; /* it's a little odd that you have named your node struct list */
    struct list * new;

    while(marker && marker->data != where) /* we don't want to end up dereferencing a null pointer */
        marker = marker->next;

    if (!marker) /* we've reached the end of the list and no element was found */
    {
        printf("Element with data %d not found\n", where); /* print some diagnostics */
        return; /* let's exit here, no reason to hang about */
    }

    /* if we are here then we've found our element */

    struct list * next_node = marker->next; /* let's save the next node */

    new = malloc(sizeof(struct list)); /* it is bad practice to cast the result of malloc */
    new->data = d;

    marker->next = new; /* marker now points to the new node */

    new->next = next_node; /* the new node now points to the one marker originally pointed to */
}

关于演员表,请在此处malloc阅读。

于 2013-07-10T01:17:01.000 回答
0

也许你可以像这样修改你的代码(第一个节点是第 0 个节点,第二个节点是我这段代码中的第 1 个节点):

void insertAfter(int d, int where )  
{
    struct list * marker = head;
    struct list * new;
    int count = 0;

    while(count < where)
    {
        count++;
        marker = marker -> next;
    }
    new = (struct list*)malloc(sizeof(struct list));

    new -> next = marker -> next; 
    marker -> next = new;
    new -> data = d; 
}
于 2013-07-10T01:05:54.373 回答
0

您的代码是在 data==where 的节点之后插入新节点,而不是 where'th 节点。你可以这样写:

int i;
for(i=1; i<where; i++)
    marker = marker->next;

此外,最好检查是否marker到达 a NULL,否则当程序尝试读取marker->nextormarker->data时,将中止。

于 2013-07-10T05:18:31.807 回答