codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#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; }
Private
[
?
]
Run code
Submit