The need:
This program is written just to show the use of linked lists. This program takes some numbers from the user stores them in nodes (creates linked list) and prints back for the user in the same order. So this program teaches us creating and accessing linked lists.
This program is written just to show the use of linked lists. This program takes some numbers from the user stores them in nodes (creates linked list) and prints back for the user in the same order. So this program teaches us creating and accessing linked lists.
--------------------------------------------
#include<stdio.h> #include<stdlib.h> struct node1 { int data; struct node1 *next; }; typedef struct node1 node; //defining a datatype node int main() { int i,j; node *head,*temp1,*temp2; //declaring 3 pointers of type node head=NULL; //initialising head to null printf("Enter numbers to be stored. enter -999 to end.\n"); while(i!=-999) //this while loop takes the numbers and creates list { //loop runs untill user enters -999 scanf("%d",&i); temp1=(node*)malloc(sizeof(node)); //allocation of a temporary node temp1->data=i; //filling data in node temp1->next=NULL; /*making pointer to next location NULL because there is no next location till now*/ if(head==NULL) //the case when temp1 is very first node { head=temp1; //so head will be containing the address of first node permanently temp2=head; //temp2 is temporarily given address of first node } else /*the case when temp1 is not first node, we have a list of some members. Its kind of a line of persons in which a newcomer has to stand at the last so we have to go to last position starting from first*/ { while(temp2->next!=NULL) //checking if temp2 is last node temp2=temp2->next; //loop exits if temp2 is last node temp2->next=temp1; //temp1 is appended to the list after last node } } printf("All the numbers has been entered into linked list.\n"); printf("press any key to view the list\n"); fflush(stdin); //to flush previous undesired inputs from keyboard getchar(); //to give a pause to program untill user press any key printf("\nThe list is\n\n"); temp2=head; while(temp2->next!=NULL) //this loop prints the list { printf("%d-->",temp2->data); //printing current member temp2=temp2->next; //jumping to next member in the list } printf("\n"); return 0; }--------------------------------------------
The approach:
The approach is very simple once you have read previous post. Everything has been written near statements as comments. Still this is a new topic so in case of any doubt please let me know.
No comments:
Post a Comment
feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply