Thread: Linked lists--do these programs both clear the list?

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    25

    Linked lists--do these programs both clear the list?

    What is the difference between these programs? I am studying for an exam and I think the 2nd one is easier to follow, its recursive I know that...



    Code:
    void ResetList(struct point **ptrFirst, struct point **ptrLast) {
       struct point *current = *ptrFirst;
       struct point *next = NULL;
    
       // free up all the memory in the list
       while (current != NULL) {
          next = current->ptrNext;
          free(current);
          current = next;
       }
    
       // update the first and last pointers, which still point to the freed memory
       *ptrFirst = NULL;
       *ptrLast = NULL;
    }
    Code:
    // user must clear ptrFirst and ptrLast
    void ClearList(struct node * ptrF)
    {
    	// base case: empty list
    	if (ptrF == NULL)
    		return;
    	else
    	{
    		ClearList(ptrF->ptrNext);
    		free(ptrF);
    	}
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Look at the last 2 lines of your ResetList function. Notice there's nothing like that in ClearList.

    ClearList has the same number of lines of code (excluding the curly braces) if you ignore setting ptrFirst and ptrLast to NULL. Maybe a little "clearer", but not much, IMO.

    What do you think might happen if you call ClearList with a list having 1,000,000 elements?

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by anduril462 View Post
    What do you think might happen if you call ClearList with a list having 1,000,000 elements?
    A rather large spike in Kevlar sales after the boss finds out?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-01-2010, 10:19 PM
  2. Linked Lists with multiple programs
    By crimsonpetal13 in forum C Programming
    Replies: 21
    Last Post: 02-22-2010, 10:56 PM
  3. Linked List!!!Error in Clear() function!!please help me..
    By zaracattle in forum C++ Programming
    Replies: 3
    Last Post: 10-09-2006, 01:11 PM
  4. Linked List of Linked lists Revisited.
    By Qui in forum C++ Programming
    Replies: 11
    Last Post: 04-11-2004, 09:45 PM
  5. Clear Function on Linked List
    By s0ul2squeeze in forum C++ Programming
    Replies: 1
    Last Post: 04-04-2002, 07:13 AM