Professional Documents
Culture Documents
How To Create A Linked List in C
How To Create A Linked List in C
it might be, and without wasting memory by allocating elements you don't have yet.
The downside is that you have to do all the work of organizing and managing the list
in memory.
Difficulty: Easy
Instructions
Create the Data Structure
1. 1Choose a name, then use typedef to define it. Every linked list will need a
structure, even if it only has one variable:
2. 2Define the structure. The last element should be a pointer to the type you just
defined, and named "next":
struct product_data {
int product_code;
int product_size;
PRODUCT_DATA *next;
};
PRODUCT_DATA *newproduct;
6. 3Populate the new element's fields. Set its "next" field to NULL:
newproduct->product_code = newcode;
newproduct->product_size = newsize;
newproduct->next = NULL;
7. 4Set the head variable. If the head variable is NULL, this is the first element
added to the list, so set the head variable to point to it:
8. 5Prepare for a different variable. In other cases, the tail variable points to the
last item on the list, so set its next value to point to the new item:
else products_tail->next = newproduct;
9. 6Update the tail to point to the new last element, in either case:
products_tail = newproduct;
PRODUCT_DATA *product;
product = products_head;
12. 3Loop through the elements, checking each one and then setting the temporary
variable to the next pointer to traverse to the next one:
13. 4Check if the variable is NULL. If so, you never found the item:
if (!product) return 0;
return product->product_size;
14. 1Deallocate the list when your program ends, as not all operating systems will
handle this automatically.
15. 2Loop as long as the head variable is not NULL:
while (products_head) {
products_tail = products_head->next;
free(products_head);
18. 5Set the head pointer to the pointer you saved in step 4:
products_head = products_tail;
}