I'm writing a program that will alternate printing out data between two linked lists into a third list. Actually I have to write a function that will do it.
I wanted to test it out, so I created two lists with test number in them in main and started to write my function, but I have to pass the head pointer for each of the linked lists by reference and I'm stuck on what I need to do with the third pointer.
Anyway, if list 1 has the numbers 1, 3, 5, 7 and list 2 has the numbers 2, 4, 6, 8 the third list will print out 1, 2, 3, 4, 5, 6, 7, 8. Any extra values are to be omitted.
Here's what I've got so far:
I wanted to test it out, so I created two lists with test number in them in main and started to write my function, but I have to pass the head pointer for each of the linked lists by reference and I'm stuck on what I need to do with the third pointer.
Anyway, if list 1 has the numbers 1, 3, 5, 7 and list 2 has the numbers 2, 4, 6, 8 the third list will print out 1, 2, 3, 4, 5, 6, 7, 8. Any extra values are to be omitted.
Here's what I've got so far:
Code:
#include <iostream> using namespace std; struct node{ int data; node *next; }; void interleave(node*,node*,node*); void main(){ node * head1; node * list1_1; list1_1 = new node; head1 = list1_1; list1_1->data = 2; list1_1->next = NULL; node * list1_2; list1_2 = new node; list1_2->data = 5; list1_1->next = list1_2; list1_2->next = NULL; node * list1_3; list1_3 = new node; list1_3->data = 7; list1_2->next = list1_3; list1_3->next = NULL; node * list1_4; list1_4 = new node; list1_4->data = 9; list1_3->next = list1_4; list1_4->next = NULL; //******************************************** node * head2; node * list2_1; list2_1 = new node; head2 = list2_1; list2_1->data = 3; list2_1->next = NULL; node * list2_2; list2_2 = new node; list2_2->data = 6; list2_1->next = list2_2; list2_2->next = NULL; node * list2_3; list2_3 = new node; list2_3->data = 8; list2_2->next = list2_3; list2_3->next = NULL; //******************************************** /*while(head1){ cout<<head1->data<<endl; head1 = head1->next; } cout<<endl<<endl; while(head2){ cout<<head2->data<<endl; head2 = head2->next; }*/ interleave(head1,head2,head3); } void interleave(node*head1, node*head2, node*head3){ while(head1 || head2 != NULL){ node * head3; head3 = new node; head3 = head1; head3->next = head2; cout<<head3; } }
Comment