UnsortedList MergeSortedList l1 SortedList l2 Function Ret
UnsortedList Merge(SortedList l1, SortedList l2 ) - Function: Returns a list that is the result of merging the elements of l1 with those of list l2. - Precondition: Lists l1 and l2 have been initialized. - Postcondition: Function value = a new list containing elements of l1 merged with elements of l2.
Solution
Program code:
#include<stdlib.h>
#include<stdio.h>
typedef struct node
{
int R; // declare our data R is integer value
struct node *nxt;
}
Node;
Node *mergeSort(Node *x, Node *y)// here declare the two nodes x,y to be merge
{
Node *res=NULL;// set the result node as null
if(x==NULL)
return y;// return y when the x node is null value
else if(y==NULL)
return x;// return x when the x node is not null
if(x->R <=y->R)//set the result to either x or y
{
res = x;
res->nxt=mergeSort(x->nxt,y);
}
else
{
res = y;
res->nxt=mergeSort(x,y->nxt);
}
return res;
}
Node * createNode(int val)
{
Node * temp = (Node *)malloc(sizeof(Node));
if(temp)
{
temp->R = val;
temp->nxt = NULL;
}
return temp;
}
/*insert node at the head of linked list */
void push(Node **headRef, int R)
{
Node * newNode = createNode(R);//create node for our data
newNode->nxt = *headRef;//declare headRef for next new node
}
void printList(Node * head)
{
while(head)
{
printf(\"%d->\" , head->R);
head = head->nxt;
}
printf(\"NULL\");
printf(\"\ \");
}
/*here goes main program*/
int main()
{
Node * List1 = NULL;//node list 1 set as to be null
Node * List2 = NULL;//node list 2 set as to be null
Node * res = NULL;//here set result as null
int carry = 0;
push(&List1,7);//here the list 1 creating
push(&List1,6);
push(&List1,4);
push(&List1,3);
push(&List2,10);//here the list 2 creating
push(&List2,8);
push(&List2,1);
return 0;
}


