Thread: Inserting to sorted linked list

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    ---
    Join Date
    May 2004
    Posts
    1,379

    Inserting to sorted linked list

    Hi all.

    Been a long time since I posted here and I'm a bit rusty with my C.
    I'm trying to write a function that inserts into a linked list where node->name is in alphabetical order.

    This is what I have so far and it seems logical to me but I just can't understand why they are not sorted.

    Code:
    void insertProductNode(char *brand, char *name, unsigned price, unsigned qty, ProductNodeType **head){
       ProductNodeType *node = malloc( sizeof(ProductNodeType) );
       ProductNodeType *iter = *head;
    
       if( node == NULL ){
          fprintf(stderr, "Error allocating memory. addProductNode()");
          exit(EXIT_FAILURE);
       }
    
       strncpy( node->brand, brand, PRODUCT_BRAND_MAX );
       strncpy( node->name, name, PRODUCT_NAME_MAX );
       node->qty = qty;
       node->price = price;
       node->nextProduct = NULL;
    
       if( iter == NULL ){
          *head = node;
       }
       else{
          while( iter != NULL ){
             if( iter->nextProduct == NULL ){
                iter->nextProduct = node;
                break;
             }
             else if ( strcmp( node->name, iter->name ) < 0){
                node->nextProduct = iter->nextProduct;
                iter->nextProduct = node;
                break;
             }
             iter = iter->nextProduct;
    
          }
    
       }
    }
    Code:
    typedef struct productNode
    {
       char name[PRODUCT_NAME_MAX + 1];
       char brand[PRODUCT_BRAND_MAX + 1];
       unsigned price;
       unsigned qty;
       struct productNode* nextProduct;
    } ProductNodeType;
    Last edited by sand_man; 05-04-2012 at 09:13 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating a Sorted Linked List
    By jeanermand in forum C Programming
    Replies: 2
    Last Post: 12-04-2011, 11:39 PM
  2. sorted linked list
    By budala in forum C Programming
    Replies: 12
    Last Post: 07-29-2009, 08:47 AM
  3. inserting in a sorted list
    By angelscars in forum C++ Programming
    Replies: 16
    Last Post: 11-11-2005, 04:33 PM
  4. Inserting new nodes in a sorted double linked list
    By carrja99 in forum C++ Programming
    Replies: 2
    Last Post: 03-07-2003, 08:34 AM
  5. sorted linked list
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 02-03-2002, 09:11 PM