Thread: Understanding a Linked List Destroy() Function

  1. #1
    Registered User
    Join Date
    Jun 2017
    Posts
    1

    Understanding a Linked List Destroy() Function

    Hi, i'm now learning both pointers and structs (linked lists) lately, and have an example of a destroy function() for a given linked list. Would somebody mind explaining the processes within the function conceptually to me with as much detail as possible?

    Given a node struct:
    Code:
    typedef struct node Node;
    struct node
    {
         int data;
         Node *next;
    };
    Code:
    void destroy(Node *head)  //passes entire Node struct? what does *head point to?
    {
         Node *temp;         //Confused on what this does
         while(head!=NULL);  
         {
              temp=head;
              head=head->next;
              free(temp);
         }
    }
    Thanks!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,213
    Conceptually, each node is a stepping stone across a river.

    You want to pull up each stone as you go because you don't want to be followed.

    temp=head;
    Make a note of where you're standing.

    head=head->next;
    Jump to the next stone.

    free(temp);
    Remove the one you were standing on!
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help understanding linked list behavior
    By KBriggs in forum C Programming
    Replies: 7
    Last Post: 07-06-2015, 01:03 PM
  2. Linked List - Still not understanding!
    By stach in forum C Programming
    Replies: 4
    Last Post: 08-12-2013, 08:08 AM
  3. help understanding linked list
    By progmateur in forum C Programming
    Replies: 4
    Last Post: 03-19-2013, 02:02 PM
  4. Doubly Linked List - Understanding...
    By hi-0ctane in forum C Programming
    Replies: 3
    Last Post: 05-31-2009, 05:27 PM
  5. understanding linked list
    By sara.stanley in forum C Programming
    Replies: 5
    Last Post: 04-14-2006, 04:32 PM

Tags for this Thread