Thread: deleting a linked list

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    48

    deleting a linked list

    i'm hoping i'm wrong here but to delete a linked list you have to make a delete command on each the pointer for each node yes?

    so does that mean that to fully delete a linked list you actually need to have stored somehow the pointers for the node that comes above the node your deleting (if you start at the last node, the 'bottom' of the list) or does anyone know a better way i'm not thinking of?
    astride a storied past, thats everywhere you are

  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    151
    You could delete it top down, as long as you remember to store the next node for moving up before deleting the existing top.

  3. #3
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    Code:
    class Node
    {
         private:
         int data;
         Node* next;
    
         friend class List;
    };
    
    class List
    {
         public:
         //functions and stuff
    
         private:
         Node* head;
         Node* tail;
    };

    Assuming your list is like those I have encountered you would normally delete each node via the link (called next in Node class). The code will be kinda like this:
    Code:
    void List::~List( )
    {
         Node* toGo;  //pointer to node to be deleted
    
         while( head != tail )
         {
               toGo = head;
              head = head->next;
              delete toGo;
         }
    }

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    48
    duh...i can be such a donut once it hits midnight. need coffee...
    astride a storied past, thats everywhere you are

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  3. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM