The need:
This program is the same previous program written using User Defined Functions (UDFs). 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 the same previous program written using User Defined Functions (UDFs). 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 void printlist(node *p); //udf to print list void add_node(int a,node *p); //udf to add node to last of list node *create_node(int); //udf to create a new node int main() { int i,j; node *head; //head will be first node of list 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); if(head==NULL) //if i is first node head=create_node(i); //creates a new node and assigns its address to head else add_node(i,head); } 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"); printlist(head); //UDF to print the linked list printf("\n"); return 0; } void printlist(node *p) { node *temp=p; while(temp->next!=NULL) //this loop prints the list { printf("%d-->",temp->data); //printing current member temp=temp->next; //jumping to next member in the list } printf("END"); } void add_node(int a,node *p) { node *temp1,*temp2; temp2=p; /*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*/ temp1=create_node(a); 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 } node *create_node(int b) { node *temp1; temp1=(node*)malloc(sizeof(node)); //allocation of a temporary node temp1->data=b; //filling data in node temp1->next=NULL; /*making pointer to next location NULL because there is no next location till now*/ return temp1; //return }--------------------------------------------
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. Now onward I'll use UDFs to do deal with linked lists.