2017-11-25 111 views
0

這是我迄今爲止,但它不是在測試文件上工作。基本上跳到別的if(cnode == preposition)如何刪除鏈接列表中的節點?

void LinkedList::Delete(Node *PrePosition) { 

    Node *cnode = head; 
    Node *pnode = NULL; 
    while (cnode != NULL) { 
     if (cnode->value != NULL) { 
      if (pnode == NULL) { 
       //if there is not previous node 
       head = cnode->next; 
      } 
      else if(cnode == PrePosition){ 
       //if there is previous node 
       cout << endl << "Deleting: " << cnode << endl; 
       pnode->next = cnode->next; 
      } 
     } 
     else { 
      //dont delete 
      pnode = cnode; 
     } 
     cnode = cnode->next; 

    } 

} 

回答

3

1:從以前的節點帶指針,它指向要刪除

2一前一後的下一個:從以前的節點刪除指針當前節點

3:刪除從下一個節點的指針到當前節點(如果它是一個雙向鏈表)

+1

順便說一句,有關於geeksforgeeks.com的額外信息 – 2017-11-25 23:13:23

+0

最好是將更多信息(包括鏈接)編輯到您的答案中,而不是將其添加爲評論 – PiedPiper

+0

@PiedPiper,對不起,我對此很新穎,我請記住:) – 2017-11-26 21:10:02

1

三起案件在單鏈表中刪除的:

  1. codementor刪除第一個節點

    void delete_first() 
    { 
        node *temp=new node; 
        temp=head; 
        head=head->next; 
        delete temp; 
    } 
    
  2. 刪除最後一個節點

    void delete_last() 
    { 
        node *current = new node; 
        node *previous = new node; 
        current=head; 
        while(current->next != NULL) 
        { 
         previous = current; 
         current = current->next; 
        } 
        tail = previous; // if you have a Node* tail member in your LinkedList 
        previous->next = NULL; 
        delete current; 
    } 
    
  3. 刪除在特定的位置(你的情況)

    void LinkedList::delete_position(int pos) 
    { 
        node *current=new node; 
        node *previous=new node; 
        current=head; 
        for(int i=1; i < pos; i++) //or i = 0; i < pos-1 
        { 
         previous=current; 
         current=current->next; 
        } 
        previous->next=current->next; 
    } 
    

    ^^ ^^

但是,如果你的函數簽名打算delete_node(Node* nodeToDelete) [介詞是不是一個好名字在這種情況下]你想刪除傳遞給函數的節點在不知道我們可以修改delete_position(在列表中的位置),像這樣:

void LinkedList::delete_node(Node* nodeToDelete) 
{ 
    if (head == nodeToDelete){ 
     head = nodeToDelete->next; 
     return 
    }//else: 
    node *current=new node; 
    node *previous=new node; 
    current=head; 
    while(current != nodeToDelete) 
    { 
     previous = current; 
     current = current->next 
    } 
    previous->next = current->next; 
} 

另外在你的原代碼,如果它跳過你所提到的線,pnode總是空當cnode中有一個非空值。

+0

如果你已經有一個指針到以前的位置,爲什麼重複列表,找到了嗎? – user4581301

+0

@ElfenDew現在我感覺不好,因爲我的票比你多。 – 2017-11-26 04:28:12