Linked list: Delete node

1.新增一個指向head的指針, 將指針移動到目標

  • 當指針不指向NULL時, 且指針的值或是index不為目標時

    • 指針 = 指針 -> next

2.刪除目標

  • 需要兩個node: current, previous,分別指向目標及目標的前一個node

  • 目標為第一個node

  • 目標不為第一個node

    void Delete(int x, ListNode * first){
        ListNode *current = first, *previous = 0;
        while (current != 0 && current->data != x) {  // Traversal
            previous = current;                       // 如果current指向NULL
            current = current->next;                  // 或是current->data == x
        }                                             // 即結束while loop

        if (current == 0) {                 // list沒有要刪的node, 或是list為empty
            std::cout << "There is no " << x << " in list.\n";
            // return;
        }
        else if (current == first) {        // 要刪除的node剛好在list的開頭
            first = current->next;          // 把first移到下一個node
            delete current;                 // 如果list只有一個node, 那麼first就會指向NULL
            current = 0;                    // 當指標被delete後, 將其指向NULL, 可以避免不必要bug
            // return;                     
        }
        else {                              // 其餘情況, list中有欲刪除的node, 
            previous->next = current->next; // 而且node不為first, 此時previous不為NULL
            delete current;
            current = 0;
            // return;
        }
    }

Last updated