samedi 18 avril 2015

Insert node not values in end of linked lists

Lets say I have some linked lists already available and I want to store first node of each individual list into another list so that I can recall this list to display the original lists. I think we have to use two different structures. I am already successful in retaining original lists and displaying them using Array of first nodes of individual lists but I want to create a linked list of individual list to implement same. It has the expected output but as I said I want to use linked list instead of array of nodes.


Here is the code:



#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct node{
int number;
struct node*next;
};

typedef struct node Node;
Node* insertValue(Node * list, int value);
void display(Node*);

int main()
{

Node *globalList = NULL, *lists[100];
int nbrOfLists, listNo, nbrOfVal, valNo, val,i=0,k;

CHECKER:
printf("\n\n Enter the number of lists (1 to 100):");
scanf("%d", &nbrOfLists);

if(nbrOfLists <= 0 || nbrOfLists > 100) //handling exceptional cases
{
printf("\n \n Number of Lists should be between 1 to 100"); // since array of node pointers contains 100 elements
goto CHECKER;
}


for(listNo = 0; listNo < nbrOfLists; listNo++)
{
printf("\n\n Enter the number of inputs to the list %d: \n ",listNo+1);
scanf("%d", &nbrOfVal);
lists[listNo] = NULL;

for(valNo = 0; valNo < nbrOfVal; valNo++) // to enter values in each individual list
{
printf("Enter node value %d:", valNo+1);
scanf("%d", &val);

// Here we insert the value in both lists
lists[listNo]= insertValue(lists[listNo], val); // original list has to be retained so storing in array lists
globalList = insertValue(globalList, val); // inserting node in combined list. This prevents an extra loop and merges the list elements into one.
}

printf("\n The list %d is: ",listNo+1);
display(lists[listNo]); // display each list after input
}

printf("\n\n\n THE FINAL LIST IS: ");
display(globalList); //display combined list

printf("\n\n THE LISTS WERE: ");

while(i<nbrOfLists){ //original lists displayed
k=i+1;
printf("\n\n The list %d is: ",k);
display(lists[i]);
i++;
}

printf("\n\n");
return 0;
}

Node* insertValue(Node * list, int value) // function to insert node in ordered manner into list
{
Node *newNode, *m;
newNode = malloc(sizeof(Node));
newNode->number=value;

if(list == NULL)
{
newNode->next=NULL; // inserting first node
return newNode;
}

if(value < list->number)
{
newNode->next = list; // inserting in end
return newNode;
}

m = list;
while(m->next) // checking for right position in ordered list for new node
{
if(value < m->next->number)
break;
m = m->next;
}
newNode->next = m->next; // inserting new node
m->next = newNode;
return list;
}

void display(Node*nodex){ // display node values in list

printf("%d ->",nodex->number);
nodex=nodex->next;

if(nodex)
return display(nodex);
else
return 0;
}

Aucun commentaire:

Enregistrer un commentaire