hi
so i have to make a copy of a linked list i made last week and this time i just have to update it with a deep copy concept thus making a copy of that list i made. here is my code:
#include <iostream>
#include <string>
using namespace std;
struct listrec // one node of singly-linked list
{
int value;
listrec *next; // next is pointer variable that points to the next node in the list
};
void deepcopy(listrec *old_linked_list, listrec *&new_linked_list)
{
// perform a deep copy from old_linked_list to new_linked list
while (old_linked_list != NULL)
{
new_linked_list->value = old_linked_list->value;
new_linked_list->next = old_linked_list->next;
old_linked_list = old_linked_list->next;
new_linked_list = new_linked_list->next;
}
}
void main()
{
listrec x1, x2, x3; // creating 3 nodes
x1.value = 4; x2.value = 5; x3.value = 3;
x1.next = &x2; // set up a link from x1 to x2
x2.next = &x3; // set up a link from x2 to x3
x3.next = NULL; // specify the end of the linked list
// inserting a node
listrec x4; x4.value = 6;
x1.next = &x4;
x4.next = &x2;
listrec *head_old, *head_new = NULL;
head_old = &x1; //*beginning memory address of the old linked list*/
head_new = head_old;
deepcopy(head_old, head_new);
// Old list cout
cout << "This is the x1, x4, x2, and x3 nodes linked list: ";
while (head_old != NULL)
{
cout << head_old->value << " ";
head_old = head_old->next;
}
cout << endl << endl;
// print out the information in the linked list pointed by head_new; copied list cout
cout << "Copied list: ";
while (head_new != NULL)
{
cout << head_new->value << endl;
head_new = head_new->next;
}
cout << endl << endl;
system("pause");
}
when i run it, it runs fine, but only the old list is listed, the copied list has nothing cputed next to it. whats going on? i have a feeling its the x4 node that i passed next after x1 and before x2...if so, how do i go by fixing it? i know that its a very tiny mistake here, but what is it and how do i go about fixing it?
thnx!