input is
7 4 3 1
10 8 2 0
output is
0->2->8->10->1->3->4->7->
0->2->8->10->1->3->4->7->
expected output is
1->3->4->7->
0->2->8->10->
0->1->2->3->4->7->8->10->
but i can’t get it
the code is below
#include
using namespace std;
class node{
public:
int data;
node*next;
//constructor
node(int d){
data = d;
next = NULL;
}
};
void build(){
}
void insertathead(node*&head,int d){ //we need to except the head pointer and int data
if(head==NULL){
head = new node(d);
return;
}
node *n = new node(d); //n is the pointer that points to this new node
n->next = head;
head=n;
}
void print(node*head){ //here we r passing the head by value
while(head!=NULL){
cout<<head->data<<"->";
head = head->next;
}
cout<<endl;
}
int length(node*head){
int cnt=0;
while(head!=NULL){
cnt++;
head=head->next;
}
return cnt;
}
node* take_input_file(){
int d;
node*head=NULL;
while(cin>>d){ // this is a way to take input till end of the file
insertathead(head,d);
}
return head;
}
ostream& operator<<(ostream &os,nodehead){
print(head);
return os;
}
istream& operator>>(istream &is,node&head){
head = take_input_file();
return is;
}
node* merge(nodea, nodeb){
//base case
if(a==NULL){
return b;
}
if(b==NULL){
return a;
}
//we take another pointer not taking another LL but a new head value
node*c;
if(a->data < b->data){
c = a;
c->next = merge(a->next,b);
}
else{
c = b;
c->next = merge(a,b->next);
}
return c;
}
int main() {
nodea;
nodeb;
cin>>a>>b;
cout<<a<<b;
node* newHead = merge(a,b);
cout<<newHead<<endl;
return 0;
}