-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergingSortedLinkedList.cpp
60 lines (52 loc) · 1.36 KB
/
MergingSortedLinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**********
* Following is the Node class that is already written.
class Node{
public:
int data;
Node *next;
Node(int data){
this -> data = data;
this -> next = NULL;
}
};
*********/
Node* mergeTwoLLs(Node *head1, Node *head2) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input is handled automatically.
*/
Node* FinalHead = NULL ; //Depicting the Head of Final Sorted Linked List
Node* FinalTail = NULL ; //Depicting the Tail of the Final Sorted Linked List .
while(head1!=NULL && head2!=NULL)
{
if(head1->data<head2->data){
if(FinalHead==NULL && FinalTail==NULL)
{
FinalHead = head1 ;
FinalTail = head1 ;
head1=head1->next ;
}else{
FinalTail->next=head1 ;
FinalTail=head1 ;
head1=head1->next ;
}
}else{
if(FinalHead==NULL && FinalTail==NULL){
FinalHead=head2 ;
FinalTail=head2 ;
head2=head2->next ;
}else{
FinalTail->next=head2 ;
FinalTail = head2 ;
head2=head2->next ;
}
}
}
if(head2==NULL){
FinalTail->next=head1 ;
}else{
FinalTail->next=head2 ;
}
return FinalHead ;
}