如何将链表插入另一个链表?

时间:2016-12-24 19:42:43

标签: c linked-list

我想编写一个函数,允许我将链表插入到某个位置的另一个链表中,这样如果链表是:

list1: [1]->[2]->[3]->NULL
list2: [4]->[5]->[6]->NULL

然后调用函数:

insertList(list1, list2, 1);

修改list1,以便:

list1 = [1]->[4]->[5]->[6]->[2]->[3]->NULL

和list2保持不变且可用。

这是结构定义:

struct _node {
    int item;
    struct _node *next;
}


struct _list {
    struct _node *head;
    struct _node *last;
}

这是我的尝试,由于我遇到了段错误,因此无效。

void insertList(struct _list *list1, struct _list *list2, int pos) {
    assert(list != NULL && list2 != NULL);

    int currPos = 0;
    struct _node *curr = list1->head;

    if (pos < 0 || pos >= numLines(list1)) {
        abort();
    }

    // traverse linked list to get to correct position
    while (curr != NULL && currPos != pos) {
        curr = curr->next;
        currPos++;
    }

    struct _node *temp = curr->next;
    curr->next = list2->head;

    while (curr != NULL) {
        curr = curr->next;
    }

    curr->next = temp;

    // updating last
    curr = list1->head;
    while (curr != NULL) {
        curr = curr->next;
    }
    list1->last = curr;
}

1 个答案:

答案 0 :(得分:2)

curr

- &GT;在此位置NULLcurr->next = temp; //NULL->next gives you seg fault. ,然后您执行

while (curr->next != NULL){
 ... 
 }

你可能想要

 while (curr != NULL) {
    curr = curr->next;
}
list1->last = curr;  //here also curr is NULL, you need to rull the loop
                     //till curr->next!=NULL

您还必须更改最后一部分

{{1}}