/* lin ked_list_4.c * * Write a C Program to create a linked list and display the linked_list elements on the screen. * A linked-list is an ordered set of data elements, each containing a link * to its next node. */ #include // needed to print anything on the screen #include // .h file to allocate additional memory when a new node is to be created // #include void main() // main function returns nothing { struct node // the structure that creates, adds and sisplays a node { int num; // any variable struct node *ptr; // pointer to the next node }; typedef struct node NODE; // NODE is declared to be of type struct node NODE *head, *first, *temp = 0; // *head, *first, *temp are all variables of type struct node int count = 0; // just a counter int choice = 1; // choice variable first = 0; // points to root while (choice) // while choice is 1, keep creating new node { head = (NODE *)malloc(sizeof(NODE)); // head points to the beginning of the allocated new memory printf("Enter the data item\n"); // a data item is entered and assigned to num in struct node scanf("%d", &head->num); // value entered from keyboard if (first != 0) // if the initial node exists { temp->ptr = head; // head points to the newly allocated memory block and assigned to temp->ptr temp = head; // head is stored in a temporary location called temp } else // if first == 0, no node exists, hence create a new node { first = temp = head; // first, temp and head points to nowhere (or zero memory) } fflush(stdin); // whatever entered from keyboard, display it on the screen printf("Do you want to continue(Type 0 or 1)?\n"); // continou to enter new node, hence data scanf("%d", &choice); // assign entered value to choice } temp->ptr = 0; // temp->ptr initially points to nowhere temp = first; // reset temp to the beginning, identified by first */ printf("\n status of the linked list is\n"); while (temp != 0) // while temp points somewhere such as beginning of the allocated memory block { printf("%d=>", temp->num); // print the value entered from the keyboard count++; // increment counter temp = temp -> ptr; // store temp->prt in a tremporary location } printf("NULL\n"); // print null printf("No. of nodes in the list = %d\n", count); }