在第n个元素后插入链接列表

时间:2013-07-10 00:51:40

标签: c linked-list

我正在使用Linked List并尝试在where节点之后插入一个带有数据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; 
}

3 个答案:

答案 0 :(得分: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的演员,请阅读here

答案 1 :(得分: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; 
}

答案 2 :(得分:0)

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

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

此外,最好检查marker是否达到NULL,或者当程序尝试阅读marker->nextmarker->data时,会有中止。