Deleting a middle node from a single linked list when pointer to the previous node is not available

前端 未结 24 1353
陌清茗
陌清茗 2020-11-29 20:42

Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to

24条回答
  •  情歌与酒
    2020-11-29 21:14

    You have the head of the list, right? You just traverse it.

    Let's say that your list is pointed to by "head" and the node to delete it "del".

    C style pseudo-code (dots would be -> in C):

    prev = head
    next = prev.link
    
    while(next != null)
    {
      if(next == del)
      {
        prev.link = next.link;
        free(del);
        del = null;
        return 0;
      }
      prev = next;
      next = next.link;
    }
    
    return 1;
    

提交回复
热议问题