How to delete a node in a linked list?

后端 未结 3 1465
孤独总比滥情好
孤独总比滥情好 2021-01-23 14:33

This is what I have so far, but it\'s not working in the test file. Basically skips to the else if(cnode == preposition)

void LinkedList::Delete(Nod         


        
3条回答
  •  暖寄归人
    2021-01-23 15:01

    Three cases of delete in a singly linked-list:

    1. delete the first node

      void delete_first()
      {
          node *temp=new node;
          temp=head;
          head=head->next;
          delete temp;
      }
      
    2. delete the last node

      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. delete at a particular position (your case)

      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 current;
      }
      

      ^^ from codementor ^^

    However if your function signature intends delete_node(Node* nodeToDelete) [PrePosition is not a good name in this case] and you want delete the node passed to the function without knowing its position in the list we can modify delete_position() like so:

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

    Also in your original code, if it's skipping the line you mentioned, pnode is always null when cnode has a non-null value in it.

提交回复
热议问题