Thread: add to the beginning of a circular (singly) linked list

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    74

    add to the beginning of a circular (singly) linked list

    Hi there. Long time no read

    I have a problem with my circular list. I can add a node to the end of the list just fine, but I can't seem to add it to the beginning.

    This is (sort of a pseudocode) for my adding to the end of the list
    Code:
    if (*head == NULL)
    {
    	*head = new;
    	(*head)->next = *head;
    }
    else
    {
    	last  = *head;
    	while (last->next != *head)
    		last = last->next;
    		
    	new->next = *head;
    	last->next = new;
    }
    I tried this for adding to beginning of the list but after adding the seccond node the program just stalls.

    Code:
    if (*head == NULL)
    {
    	*head = new;
    	(*head)->next = *head;
    }
    else
    {		
    	new->next = *head;
    	*head = new;
    }

  2. #2
    Registered User
    Join Date
    Apr 2009
    Posts
    145
    Well.....I don't know how your determining beginning and end in a circular list?
    Hence
    Considering one node circular list, next pointer of first node will be pointing to itself and hence definitely not null....
    Last edited by sanddune008; 06-30-2010 at 04:26 AM.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    74
    I think I didn't make my self clear. When I said "end" i thought "after the last node in the list" or more precisely "before the beginning in the list"

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    145
    Quote Originally Posted by budala View Post


    Code:
    if (*head == NULL)
    {
    	*head = new;
    	(*head)->next = *head;
    }
    else
    {		
    	new->next = *head;
    	*head = new;
    }
    wait this is not circular.....here u need to configure the previous node's next to point the new head. Considering two nodes in a circle the next pointer of second has to point the head. Which is not happening in the lines....

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    74
    got it!

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. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  3. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

Tags for this Thread