c-在第n个元素后插入链表



我正在使用链表,并试图在第d个节点后面插入一个数据为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; 
}

我能建议一个更安全的版本并附上一些评论吗:

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 foundn", 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的铸造,请在这里阅读。

也许你可以这样修改你的代码(第一个节点是第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; 
}

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

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

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

相关内容

  • 没有找到相关文章

最新更新