Possible Duplicate:
Copy a linked list
Hello stackoverflow! I am trying to learn more about linked lists so I am trying to create a function that deep copies a linked list. I've got this under control. The hard part is that the input list is going to contain nodes that reference other random nodes within the list.
First problem is that I don't know how to create the 'random' nodes within the list. As of now, I just have the 'random' nodes equal to the 'next' nodes.
For example... pNext references the next value, but pReference will reference a random node in the list. Like pReference 1 references 3, 2 references 4, 3 references 1, and 4 references 1.
Second problem is that my code is coping the 'random' node values but it is dependent on the original copy. I want it to be a deep copy and not dependent on the original.
#include <iostream>
#include <stdio.h>
using namespace std;
struct Node
{
int Number; // An integer value.
Node *pNext; // A pointer to the next node within the list.
Node *pReference; // A pointer to a random node within the list.
};
void push(Node** head, int data, Node* reference)
{
Node* newNode = new Node;
newNode->Number = data;
newNode->pNext = *head;
newNode->pReference = reference;
*head = newNode;
}
Node* DuplicateLinkedList(Node *head)
{
Node* current = head;
Node* newHead = NULL;
Node* newTail = NULL;
while(current != NULL)
{
if(newHead == NULL)
{
push(&newHead, current->Number, (current->pReference));
newTail = newHead;
}
else
{
push(&(newTail->pNext),current->Number, (current->pReference));
newTail = newTail->pNext;
}
current = current->pNext;
}
return newHead;
}
int main()
{
Node* headOfList= NULL;
//Creating List for verification.
for(int i=6; i>=1;i--)
{
push(&headOfList, i, headOfList);
}
//Call duplicate function.
Node* copiedList = DuplicateLinkedList(headOfList);
//Output for verification
cout << endl << "Original: " << endl;
while(headOfList != NULL)
{
cout << "Number: " << headOfList->Number << " ";
cout << "pNext: " << headOfList->pNext << " ";
cout << "pReference: " << headOfList->pReference << " " << endl;
headOfList = headOfList->pNext;
}
cout << endl << endl;
cout << endl << "Copied: " << endl;
while(copiedList != NULL)
{
cout << "Number: " << copiedList->Number << " ";
cout << "pNext: " << copiedList->pNext << " ";
cout << "pReference: " << copiedList->pReference << " " << endl;
copiedList = copiedList->pNext;
}
cout << endl << endl;
system("pause");
}