Thread: Deleting all nodes of link list

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    5

    Deleting all nodes of link list

    Hi , there was a question asked in one of the interviews.. Delete all the nodes of link list..Let me know if I have written the correct code
    Code:
    struct node 
    {int data'
    struct node *next;};
    typedef struct node NODE;
    NODE head;
    
    void deleteall(){
    
    NODE *ptr;
    ptr=head;
    while (head!=NULL)
    {ptr=head;
    head=head->next;
    free(ptr);
    }
    
    
    
    }
    Here free just de allocates the memory, so I don't have to define ptr in the loop. Let me know if I am wrong.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    You will want to compile that to catch syntax errors. Other than that it looks like it should work.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    5
    Thanks. No compilation error !

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I guess you fixed the single-quote on line 2 that was clearly meant to be a semi-colon, then.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Dec 2012
    Posts
    5
    Yes

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Code:
    NODE head;
    You probably want:

    Code:
    NODE *head;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deleting nodes from a linked list
    By lildan in forum C Programming
    Replies: 4
    Last Post: 12-02-2010, 12:07 AM
  2. deleting from a linked list if there are just 2 nodes
    By Nooby in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2010, 11:55 PM
  3. deleting nodes in a linear list
    By sudhanshu_nsit in forum C++ Programming
    Replies: 7
    Last Post: 06-25-2006, 02:00 AM
  4. how to check if two link list nodes are same .. ?
    By agarwaga in forum C Programming
    Replies: 7
    Last Post: 05-24-2006, 04:11 AM