2015-10-31 66 views
-1

我嘗試結束在另一 使用此代碼末尾插入一個列表:追加鏈表到另一個

typedef struct Element 
{ 
    int vKey; 
    char vInfo[30]; 
    struct Element *pNext; 

} tsElement; 

typedef struct 
{ 
    tsElemento *pFirst; 
    int vLength; 

} tsLDSE; 

void Unir(tsLDSE *pListIn, tsLDSE *pListOut) 
{ 
    tsElement *pElementOut; 

    pElementOut = pListOut->pFirst; 

    while (pElementOut != NULL) 
    { 
     pElementOut = pElemenoOut->pNext; 
    } 

    pElementOut = pListIn->pFirst; 
    pListOut->vLength = pListOut->vLength + pListIn->vLength ; 
} 

我檢查打印不會忽略,pElementoOut是真正的第一個列表的末尾和是poiting爲NULL,然後它收到的第二個列表的fisrt地址,但是當我打印出來它只打印第一個列表,我不明白爲什麼。

+0

在*'pElemenoOut'爲'NULL'之前,您需要'pElemenoOut-> pNext = pListIn-> pFirst' *。 – user3386109

+0

謝謝,它的工作,但我不明白爲什麼 因爲pElementOut是pPrevious-> pNext並且爲空 爲什麼我不能只是pElementOut = pListIn->第一個 – user3728181

+0

'pElementOut'是一個局部變量與* pPrevious-> pNext'相同的值*,但'pElementOut'不是**'pPrevious-> pNext'。 – user3386109

回答

1

您的功能Unir僅將輸入列表的長度添加到輸出列表的長度。

這個循環:

while (pElementOut != NULL) 
{ 
    pElementOut = pElemenoOut->pNext; 
} 

只得到pElementOut爲NULL。

另外,當你編寫pElementOut = pListIn->pFirst;時,你所改變的只是局部變量pElementOut

你想做的事,而不是這是什麼:

while (pElementOut->pNext != NULL) 
{ 
    pElementOut = pElementOut->pNext; 
} 

pElementOut->pNext = pListIn->pFirst; 

這使pListIn的第一個元素在pListOut的最後一個元素結束。

另外,在函數的開頭添加一個NULL檢查!如果你不小心,你可以很容易地得到一個NULL指針解引用。

+0

謝謝,它工作:) – user3728181

相關問題