2011-05-28 74 views
0

我試過了,但是我無法讓它正常工作。我需要從鏈接列表中刪除號碼。這是我到目前爲止已經完成:從單個鏈接列表中刪除整個節點

class MatrixLL 
{ 
private: 
    struct MatrixLLElem 
    { 
     Matrix elem; 
     MatrixLLElem* next; 
     MatrixLLElem(const Matrix& m1): elem(m1), next(NULL) 
     { } 
    }; 
    MatrixLLElem* start; 
public: 
    MatrixLL(); 
    Matrix& elem(const int index); 
    int getlength(); 
    void append(const Matrix& m1); 
    void deleteelem(const int index); 
    ~MatrixLL(); 
}; 

我的其他代碼不用擔心的,因爲它完美的作品,所以這裏的deleteelem()的代碼;功能:

void MatrixLL::deleteelem(const int index) 
{ 
    if(index < 1) 
     throw "Invalid index specified."; 

    if(start == NULL) 
     throw "No element at specified location."; 

    MatrixLLElem* currP = start; 
    MatrixLLElem** prevP = NULL; 

    for(int i = 1; i < index; i++) 
    { 
     prevP = &currP; 
     if((*currP).next != NULL) 
      currP = (*currP).next; 
     else 
      throw "No element at specified location."; 
    } 
    if(prevP == NULL) 
    { 
     start = NULL; 
    } 
    else 
    { 
     (*prevP) = (*currP).next; 
    } 
    delete currP; 
} 

編輯:它減少從2長度爲0,如果我檢查......而長度功能似乎如果我追加到工作正常,然後檢查等指標應該是從1開始。

回答

2

問題是,當你要刪除的第一個元素(索引= 1)。的

代替

start = NULL; // wrong 

正確的是:

start = (*currP).next; // the second element now becomes the first element 
+0

謝謝,我已經明白了。 :) – 2011-05-29 11:18:14

0
(*prevP) = (*currP).next; 

應該

(*prevP).next = (*currP).next; 
+0

prevP是雙指針。它的意思就是這樣。如果我將其更改爲單個指針並相應地編輯代碼,那麼它將刪除這兩個指針,如果我將它指向位置1. – 2011-05-28 12:08:41

0

貌似條件和不斷變化的指針部分是錯誤的。 應該是這樣的:

MatrixLLElem* prevP = NULL; // Why ** ? 

for(int i = 1; i <= index; ++i) // Here 
{ 
    prevP = currP; 
    if((*currP).next != NULL) 
     currP = (*currP).next; 
    else 
     throw "No element at specified location."; 
} 
if(currP == start) // This would be better 
{ 
    start = NULL; 
} 
else 
{ 
    (*prevP).next = (*currP).next; // And here 
} 
delete currP; 
+0

如果索引從0開始,那麼您的代碼可能是正確的。另外,prevP是雙指針。 – 2011-05-28 12:07:15

+0

爲什麼你需要一個雙指針?那麼,你可以做到這一點...但我認爲雙指針更容易出錯。 – rambo 2011-05-28 12:10:58

1

我猜中了。如果它可以幫助別人,這是代碼:

void MatrixLL::deleteelem(const int index) 
    { 
    if(index < 1) 
     throw "Invalid index specified."; 

    if(start == NULL) 
     throw "No element at specified location."; 

    MatrixLLElem* currP = start; 
    MatrixLLElem* prevP = NULL; 

    for(int i = 1; i < index; i++) 
    { 
     prevP = currP; 
     if((*currP).next != NULL) 
      currP = (*currP).next; 
     else 
      throw "No element at specified location."; 
    } 

    if(prevP != NULL) 
    { 
     (*prevP).next = (*currP).next; 
    } 
    else 
    { 
     start = (*start).next; 
    } 

    delete currP; 
} 

僅供參考,起始索引是1,不是0