IHYPRESS PROGRAMMING
Tutorials and C programs with code and output for beginners
c programming
HOME | ASP | C | CSS | GNUPLOT | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
CStructures & Linked Lists : Dynamically Allocated Linked Lists
<10.05>
/* This program creates a linked list of tree names. Each node contains the name of the tree and a pointer to the next tree. Nodes are dynamically allocated and are displayed in reverse order. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define NL 20 typedef struct tree { char tree_name [NL]; struct tree* next; }tree; int main (void) { /* temporary hold for tree name */ char treename[NL]; /* declaring the starting and traveling pointers */ tree *p, *start; /* list is empty at the beginning */ start = NULL; /* enter first tree name (or END) */ printf ("Enter a tree name (enter END to finish): "); fgets (treename,sizeof(treename),stdin); treename[strlen(treename)-1] = '\0'; /* add tree name to the list and keep asking for more until END */ while (strcmp (treename, "END") != 0) { /* allocate new node to hold new tree */ p = (tree *) calloc (1, sizeof(tree)); /* put tree name into new node */ strcpy (p -> tree_name, treename); /* puts pointer to previous tree into pointer element */ p -> next = start; /* updates start pointer with new tree */ start = p; printf ("Enter a tree name (enter END to finish): "); fgets (treename,sizeof(treename),stdin); treename[strlen(treename)-1] = '\0'; } /* displays list of tree in reverse order */ p = start; while (p != NULL) { printf ("%s\n", p -> tree_name); p = p -> next; } return (0); }
Hergestellt in Deutschland / Made in Germany
Enter a tree name (enter END to finish): Palm Enter a tree name (enter END to finish): Cedar Enter a tree name (enter END to finish): Elm Enter a tree name (enter END to finish): Oak Enter a tree name (enter END to finish): Spruce Enter a tree name (enter END to finish): Pine Enter a tree name (enter END to finish): Fir Enter a tree name (enter END to finish): Cherry Enter a tree name (enter END to finish): Maple Enter a tree name (enter END to finish): Ash Enter a tree name (enter END to finish): END Ash Maple Cherry Fir Pine Spruce Oak Elm Cedar Palm
COPYRIGHT © 2015-2024 IHY PRESS Frankfurt am Main 60329 Deutschland