0

我想寫以下問題的代碼:雙向鏈表插入在這兩者之間

插入每對連續元素之間的元素(鄰居的總和)?

示例:如果輸入是

12 23 34 45 for n=4 

輸出應爲:

12 35 23 57 34 79 45 

我寫的代碼是:

struct node *InsBet(node *head) { 
    node *i,*j,*t; 
    i=head; 
    while(i->next!=NULL) { 
     t = (node*)malloc(sizeof(node)); 
     t->data = i->data + i->next->data; 
     i->next = t;t->prev = i; 
     t->next = i->next;i->next->prev = t; 
     i = i->next; 
    } 
    return head; 
} 

在打印時它崩潰陣列我終奌站。

我的打印程序是:

void PrintList(node *head) { 
    node *i; 
    i=head; 
    while(i!=NULL) { 
     printf("%d ",i->data); 
     i=i->next; 
    } 
} 

回答

3

第一個問題是,你將其複製到t->next

交換機

i->next = t;t->prev = i; 
    t->next = i->next;i->next->prev = t; 

順序爲

前覆蓋 i->next
t->next = i->next; i->next->prev = t; 
    i->next = t; t->prev = i; 

詳細說明一下,假設你的鏈表中有2個元素:A-->B,並且你想添加臨時元素,所以你創建了t,但是因爲你做的第一件事就是覆蓋第一個元素(在這種情況下爲A),您將失去再次訪問B的機會。相反,您將自身的地址分配到臨時元素的前向指針中,從而創建無限循環。

第二個問題是,你只有一個鏈接,這意味着它現在將指向您剛剛添加的臨時元件推進當前指針(i),你會嘗試添加額外的臨時元素在tB之間。這將導致無限循環 - 而不是事先我通過 -

i = t->next; 
+0

對不起可以說你的程序請做什麼,你可以給更新代碼。 –

+0

仍然我的終端是現金後,你可以找到錯誤 –

+0

@RamanaUday你是對的,有第二個錯誤 - 看我最後的編輯 – Leeor

1

以上回答解釋得很不錯,但只給你一個工作代碼,在這裏你去:

PS,你不需要返回頭指針,因爲它通過引用傳遞,並沒有用於返回它

void InsBet(node *head) { 
    node *i,*t; 
    i=head; 
    while(i->next!=NULL) { 
     t = (node*)malloc(sizeof(node)); 
     t->data = i->data + i->next->data; 
     t->prev = i; 
     t->next = i->next; 
     i->next = i->next->next; 
     i->prev = t; 

     i = t->next; 
    } 
} 
+0

但是在打印過程中,我將使用head = CreateLinkedList(int n);和InsBet(頭);所以之後我會打印PrintList(頭像);所以哪些頭將在PrintList期間使用。並感謝代碼。 –

+0

一個linkedList只有一個頭。如果將它與數組進行比較,則頭是第一個元素 – Lukas