Creating a linked list using struct
#include <stdio.h> #include <stdlib.h> #include <string.h> int main()//w w w.jav a 2 s .co m { struct Product { char symbol[5]; int quantity; float price; struct Product *next; }; struct Product *first; struct Product *current; struct Product *newNode; /* Create structure in memory */ first = (struct Product *)malloc(sizeof(struct Product)); if (first == NULL) { puts("Some kind of malloc() error"); exit(1); } /* Assign structure data */ current = first; strcpy(current->symbol, "ABCD"); current->quantity = 100; current->price = 801.19; current->next = NULL; newNode = (struct Product *)malloc(sizeof(struct Product)); if (newNode == NULL) { puts("Another malloc() error"); exit(1); } current->next = newNode; current = newNode; strcpy(current->symbol, "MSFT"); current->quantity = 100; current->price = 28.77; current->next = NULL; /* Display database */ puts("Investment Portfolio"); printf("Symbol\tShares\tPrice\tValue\n"); current = first; printf("%-6s\t%5d\t%.2f\t%.2f\n", \ current->symbol, current->quantity, current->price, current->quantity*current->price); current = current->next; printf("%-6s\t%5d\t%.2f\t%.2f\n", \ current->symbol, current->quantity, current->price, current->quantity*current->price); return(0); }
The code created a second structure, linked to the first one.
The code declares the standard three structure pointers that are required for a linked-list.
NULL value caps the end of the linked list.