[ create a new paste ] login | about

Link: http://codepad.org/qDuM3TUH    [ raw code | output | fork ]

C, pasted on May 5:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PRODUCT_NAME_MAX 100
#define PRODUCT_BRAND_MAX (PRODUCT_NAME_MAX)

typedef struct productNode
{
   char name[PRODUCT_NAME_MAX + 1];
   char brand[PRODUCT_BRAND_MAX + 1];
   unsigned price;
   unsigned qty;
   struct productNode* nextProduct;
} ProductNodeType;

void print(ProductNodeType *head)
{
   while(head != NULL)
   {
      printf("%s %s\n", head->brand, head->name);
      printf("Price:\t$%u.%u\n", head->price / 100, head->price % 100);
      printf("Qty: %u\n", head->qty);
      head = head->nextProduct;
   }
}

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);
   }
 
   /* add data to newly created node */
   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){
            printf("node->name %s\niter->name %s\n\n", node->name, iter->name);
            node->nextProduct = iter->nextProduct;
            iter->nextProduct = node;
            break;
         }
         iter = iter->nextProduct;
 
      }
 
   }
}

int main()
{
   ProductNodeType *head = NULL;

   insertProductNode("Wonder", "bread", 129, 10, &head);
   insertProductNode("Uncle Ray's", "potato chips", 99, 12, &head);
   insertProductNode("Prince", "spaghetti", 240, 15, &head);
   insertProductNode("Kellog", "cereal", 129, 10, &head);

   print(head);
   
   while (head != NULL)
   {
      ProductNodeType *del = head;
      head = head->nextProduct;
      free(del); 
      del = NULL;
   }  
   return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
node->name spaghetti
iter->name bread

node->name cereal
iter->name bread

Wonder bread
Price:	$1.29
Qty: 10
Kellog cereal
Price:	$1.29
Qty: 10
Prince spaghetti
Price:	$2.40
Qty: 15
Uncle Ray's potato chips
Price:	$0.99
Qty: 12


Create a new paste based on this one


Comments: