We need to implement some shuffling of two lists. 1. Provide a function which takes two lists and shuffles them. This shuffling should go in an alternating way. First node from first list, second node front second list, third node front first list, 4th node front second list……. So on. If length of list 1 is greater than size of list 2, start again from the first node and follow the same procedure.
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next, *prev;
Node();
Node(int);
};
Node::Node(){
next = NULL;
prev = NULL;
}
Node::Node(int data){
this->data = data;
next = NULL;
prev = NULL;
}
class LL{
Node *head;
int size;
public:
LL();
void insert(int);
void remove(int);
static void shuffle(LL,LL);
void print();
};
LL::LL(){
size = 0;
head = NULL;
}
void LL::insert(int data){
Node *temp = new Node(data);
Node *curr = head;
if(curr == NULL){
temp->next = head;
head = temp;
return;
}
while(curr->next != NULL){
curr = curr->next;
}
temp->next = curr->next;
curr->next = temp;
size++;
}
void LL::remove(int data){
Node* curr = head;
Node* prev = NULL;
Node* temp = NULL;
while(curr != NULL){
if(curr->data == data){
if(prev == NULL){
temp = head;
head = head->next;
curr = head;
delete temp;
size--;
}
else{
temp = curr;
if(curr->next != NULL){
prev->next = curr->next;
}
else{
prev->next = NULL;
}
curr = curr->next;
delete temp;
size--;
}
}
else{
prev = curr;
curr = curr->next;
}
}
}
void LL::shuffle(LL list1, LL list2){
Node* curr1 = list1.head;
Node* curr2 = NULL;
int count = 0;
while(curr1 != NULL){
if(count % 2){
int temp = curr1->data;
curr1->data = curr2->data;
curr2->data = temp;
}
count++;
curr1 = curr1->next;
if(curr2 != NULL) curr2 = curr2->next;
if(curr2 == NULL){
curr2 = list2.head;
}
}
}
void LL::print(){
Node* curr = head;
while(curr != NULL){
cout<<curr->data<<" ";
curr = curr->next;
}
cout<<endl;
}
int main(){
LL list1;
LL list2;
for(int i = 1; i < 10; i++){
list1.insert(i);
}
for(int i = 11; i <= 15; i++){
list2.insert(i);
}
cout<<"List 1"<<endl;
list1.print();
cout<<"List 2"<<endl;
list2.print();
cout<<"Shuffling...\n";
LL::shuffle(list1, list2);
cout<<"List 1"<<endl;
list1.print();
cout<<"List 2"<<endl;
list2.print();
return 0;
}
Comments
Leave a comment