C - 链接列表插入

时间:2016-07-09 01:52:34

标签: c linked-list

我想创建5个nodels并在第3个和第4个之间插入一个新的nodle。这是代码..当我运行它时,我没有得到错误或输出。我做错了什么?提前谢谢。

+

3 个答案:

答案 0 :(得分:1)

root = temp = (node*)malloc(sizeof(node));//no need cast from void*
temp->data = 11;

int i;
for (i=0; i <= 3; i++){
    //don't change root
    temp->next = (node*)malloc(sizeof(node));
    temp = temp->next;
    temp->data = (i * 10);
}
temp->next = NULL;//next of last node need set to NULL 

newElement = (node*)malloc(sizeof(node));
newElement-> data = 1;

//temp = (node*)malloc(sizeof(node));//no need (this make memory leak)
temp = root->next->next;
root->next->next = newElement;
newElement->next = temp;


for(temp = root; temp; temp = temp->next){
    printf("%d\n", temp->data);
}

答案 1 :(得分:1)

创建4个新节点时,会在列表中的下游重新分配root指针,并且无法访问上游元素。 Intead,在循环之前设置temp = root,然后在循环中使用temp

            temp = root;
            int i;
            for (i=0; i <= 3; i++){
                           temp->next = (node*)malloc(sizeof(node));
                           temp = temp->next;
                           temp->data = (i * 10);
                           temp->next = NULL;
            }

答案 2 :(得分:0)

您在创建节点时正在修改root,您应该创建某种迭代器,它从root开始并被修改,以便您不会丢失初始位置。

尝试以下方法:

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

typedef struct node{
    int data;
    struct node *next;
}node;


int main(void) {
    struct node *root, *newElement, *temp, *iterator;

    // first node is created.
    root = (node*)malloc(sizeof(node));
    iterator = root;
    iterator->data = 11;

    // to create 4 nodes more after the first one is created.
    int i;
    for (i=0; i <= 3; i++){
       iterator->next = (node*)malloc(sizeof(node));
       iterator = iterator->next;
       iterator->data = (i * 10);
    }

    // new node to insert.
    newElement = (node*)malloc(sizeof(node));
    newElement-> data = 1;

    temp = (node*)malloc(sizeof(node));

    iterator = root;
    temp = iterator->next->next;

    iterator->next->next = newElement;

    newElement->next = temp;

    iterator = root;
    // print the values 
    int j;
    for(j=0; j<=4; j++){
        printf("%d\n", root->data);
        iterator = iterator->next;
    }

    return 0;
}