2014-01-19 42 views
1

我編寫了此代碼以刪除單向鏈接列表中的第一個節點。將第一個節點從鏈接列表中刪除後錯誤結果

CreateLinkedList(node **headPtr) 
{ 
    int i; 
    node *pMyNode; 
    pMyNode = (node*)malloc(sizeof(node)); //create space for first node [] 
    *headPtr=pMyNode; 
    for(i=0;i<10;i++) 
    { 
     pMyNode->element = i; //enter value [0] 
     printf("Value is %d addr is %p\n",pMyNode->element,pMyNode); 
     pMyNode->nextPtr = (node*)malloc(sizeof(node)); //[0]->[]->NULL 
     pMyNode = pMyNode->nextPtr; 
    } 
    pMyNode->nextPtr=NULL; 
} 

void PrintLinkedList(node **headPtr) 
{ 
    node *pMyNode; 
    int i; 
    pMyNode=*headPtr; 
    while(pMyNode) 
    { 
     printf("Value is %d addr is %p\n",pMyNode->element,pMyNode); 
     pMyNode = pMyNode->nextPtr; 
    } 
} 

void DeleteANode(node **headPtr) 
{ 
    node *pMyNode; //head->[]->[]->[]->NULL 
    pMyNode=*headPtr; 
    *headPtr=*headPtr->nextPtr; 
    free(pMyNode); 

} 
int main() 
{ 
    node *pNode; 
    CreateLinkedList(&pNode); 
    DeleteANode(&pNode); 
    PrintLinkedList(&pNode); 
} 

輸出我得到的是:

之前刪除

value is 0 addr is 8e75008 
value is 1 addr is 8e75018 
value is 2 addr is 8e75028 
value is 3 addr is 8e75038 
value is 4 addr is 8e75048 
value is 5 addr is 8e75058 
value is 6 addr is 8e75068 
value is 7 addr is 8e75078 
value is 8 addr is 8e75088 
value is 9 addr is 8e75098 

刪除

value is 0 addr is 8e75008 // This node should not be printed 
value is 0 addr is 8e75018 
value is 2 addr is 8e75028 
value is 3 addr is 8e75038 
value is 4 addr is 8e75048 
value is 5 addr is 8e75058 
value is 6 addr is 8e75068 
value is 7 addr is 8e75078 
value is 8 addr is 8e75088 
value is 9 addr is 8e75098 
+2

請顯示更完整的代碼。您不會顯示節點正在創建/初始化的位置,或者添加到列表以及調用所有這些的代碼。 – OldProgrammer

+1

DeletaANode意在刪除列表頭部的節點嗎?如果是這樣,爲什麼8e75018是不應該在您的示例中打印的節點; 8375008應該不是應該打印的節點? –

+0

正確。我剛剛編輯了我的帖子。 – user968000

回答

1

你的一個問題後,發表聲明如下:

*headPtr=*headPtr->nextPtr; 

->*具有更高的優先級,因此首先進行評估。取消引用指針首先,你需要括號:

*headPtr=(*headPtr)->nextPtr; 

的另一個問題是以下塊:

pMyNode=*headPtr; 
for(i=0;i<10;i++) 
{ 
    printf("Value is %d addr is %p\n",pMyNode->element,pMyNode); 
    pMyNode = pMyNode->nextPtr; 
} 

你不應該硬編碼有多少鏈接的。而是使用一個while循環和檢查NULL

pMyNode=*headPtr; 
while(pMyNode) 
{ 
    printf("Value is %d addr is %p\n",pMyNode->element,pMyNode); 
    pMyNode = pMyNode->nextPtr; 
} 
1

您的問題是在這條線DeleteANode的:*headPtr=*headPtr->nextPtr;

我相信它應該是*headPtr=(*headPtr)->nextPtr;

我不知道爲什麼你的版本則不要像你所擁有的那樣在線上拋出錯誤/警告。 * headPtr的賦值應該等待另一個指向節點的指針,並且您正在解引用headPtr-> nextPtr,從而嘗試將節點結構分配給* headPtr ?!