2016-04-14 74 views
-3

我想從列表中的給定位置刪除節點, 但我的刪除功能不起作用。 請幫我一把。從鏈表中的給定位置刪除節點

在此先感謝。

Node* Delete(Node *head, int position) 
{ 
    int count=0; 
    Node* temp, *temp1, *temp2; 
    temp = head ; 
if(head==NULL){ 
    return 0; 
    } 
else if(position == 0) 
    { 

    head = head->next; 
    free(temp); 
    return head; 
} 
    else{ 
     while(count!= position-1) 
     { 
     temp = temp->next; 
     count++; 
    } 
    temp1 = temp->next; 
    temp->next = temp1->next; 

    free(temp1); 
    return temp; 
} 

return head; 
} 
+0

*如何*它不工作?你有構建錯誤嗎?崩潰?你有沒有試過在調試器中運行?逐行瀏覽代碼以查看它錯誤的位置? –

+0

請定義所需的行爲。回報值應該是多少? – MikeCAT

+2

我的猜測:'return temp;'應該被移除。 – MikeCAT

回答

1

替換return temp;return head; 另外包括邏輯來處理,如果有節點小於位置。

3

首先,正確地設置你的代碼的格式。

然後,刪除return temp;,以便列表的前半部分不會丟失。

您也可以先刪除return head;,因爲函數在最後一部分將會執行return head;

Node* Delete(Node *head, int position) 
{ 
    int count=0; 
    Node *temp, *temp1, *temp2; 
    temp = head; 
    if(head==NULL){ 
    return NULL; 
    } 
    else if(position == 0) 
    { 
    head = head->next; 
    free(temp); 
    } 
    else{ 
    while(count!= position-1) 
    { 
     temp = temp->next; 
     count++; 
    } 
    temp1 = temp->next; 
    temp->next = temp1->next; 

    free(temp1); 
    } 

    return head; 
} 

注意return 0;是有效的,因爲0是一個空指針常量(N1256 6.3.2.3指針),並將其轉換爲指針的定義,但使用NULL是更好,因爲它會使明確表示,它正在處理用指針。

1

我只想添加到MikeCAT的答案。當節點數量少於該位置時,您還應該處理該情況。

一個這樣做可能的方式:

while(count!= position-1) { temp = temp->next; if(temp == NULL) return head; count++; }

0

刪除return tempreturn head。 此外,如果位置大於鏈接列表中的節點數,請檢查條件。 也釋放指針之前,我會建議添加temp1->next=NULL,然後free(temp1)