-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSortedLinkedList.cpp
More file actions
110 lines (97 loc) · 1.65 KB
/
mergeSortedLinkedList.cpp
File metadata and controls
110 lines (97 loc) · 1.65 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/* Program to merge two sorted linked List using extra space */
#include<stdio.h>
using namespace std;
#include<bits/stdc++.h>
struct Node{
int data;
Node *next;
Node(int x)
{
data=x;
next=NULL;
}
};
void printList(Node * head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
cout<<endl;
}
Node * mergeList(Node * head1, Node * head2)
{
Node *dummy= new Node(0);
Node * head=dummy;
while(head1!=NULL && head2!=NULL)
{
if(head1->data <=head2->data)
{
head->next=head1;
head1=head1->next;
head=head->next;
}
else
{
head->next=head2;
head2=head2->next;
head=head->next;
}
}
while(head1!=NULL)
{
head->next=head1;
head1=head1->next;
head=head->next;
}
while(head2!=NULL)
{
head->next=head2;
head2=head2->next;
head=head->next;
}
return dummy->next;
}
Node * mergeList_o1(Node *head1, Node * head2)
{
}
int main()
{
Node *head1=NULL, *head2=NULL;
Node * curr;
int size1, size2;
cin>>size1>>size2;
while(size1--)
{
int data;
cin>>data;
if(head1==NULL)
{
head1=new Node(data);
curr=head1;
}
else{
curr->next=new Node(data);
curr=curr->next;
}
}
while(size2--)
{
int data;
cin>>data;
if(head2==NULL)
{
head2=new Node(data);
curr=head2;
}
else{
curr->next=new Node(data);
curr=curr->next;
}
}
printList(head1);
printList(head2);
printList(mergeList(head1, head2));
return 0;
}