2016-12-24 132 views
2

我想編寫一個函數,可以讓我在某個位置插入一個鏈表到另一個鏈表這樣如果鏈表是:如何將鏈接列表插入另一個鏈表中?

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

我很困惑。每個「頭」都指向同一個節點,還是會有不同的頭?你是否更新'list2'的每個'head',因爲它現在是'list1'的一部分,因爲你只是複製指針而不是數據?哪裏是更新'list1'和'list2'的'tail'指針的代碼? –

+0

我以爲我必須保持list2不變,所以它的指針保持不變,因爲它必須在函數調用後保持可用。 – user6005857

+0

您的'node'結構將兩個東西 - 列表中的節點('item'和'next')以及列表的總體開始和結束('head'和'last')混合在一起。爲保持一致性,每次添加或刪除列表頭部或尾部的項目時,都必須遍歷整個列表以更新「head」和「last」指針。當您將一個列表插入另一個列表時,必須更新插入列表中的所有指針,以指向它所插入列表的頭部和尾部。等分開兩組數據。 –

回答

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

- >在這個位置currNULL,然後你做

curr->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 
+0

謝謝,但我在進行這些更改後仍然遇到seg故障。 – user6005857

+0

對於哪些輸入,你會得到seg故障?與問題中提到的一樣? –

+0

示例中的相同輸入。 – user6005857