Write a program to merge two sorted linked lists in c++ || leetcode 21
Program :
#include <iostream>
using namespace std;
class node{
public:
int val;
node* next;
node(int d){
this->val=d;
next=nullptr;
}
};
void push(node** h, int d){
node* tmp=new node(d);
tmp->next=*h;
*h=tmp;
}
void print(node* h){
while(h!=nullptr){
cout<<h->val<<" ";
h=h->next;
}
cout<<endl;
}
node* merge(node* h1, node* h2){
if(h1==nullptr)return h2;
if(h2==nullptr)return h1;
node* tmp=new node(0), *h;
h=tmp;
while(h1!=nullptr && h2!=nullptr){
if(h1->val >= h2->val){
tmp->next=h2;
h2=h2->next;
}
else{
tmp->next=h1;
h1=h1->next;
}
tmp=tmp->next;
}
while(h1!=nullptr){
tmp->next=h1;
h1=h1->next;
tmp=tmp->next;
}
while(h2!=nullptr){
tmp->next=h2;
h2=h2->next;
tmp=tmp->next;
}
return h;
}
int main() {
node* h=nullptr;
push(&h, 30);
push(&h,20);
push(&h,15);
push(&h,10);
print(h);
node* h2=nullptr;
push(&h2, 30);
push(&h2,20);
push(&h2,5);
push(&h2,1);
print(h2);
node *ans=merge(h, h2);
print(ans);
return 0;
}
0 Comments