'I am having trouble cloning a linked list, what is the problem in my code?
Structure of Node:
class Node{
public:
int data;
Node *next;
Node *arb;
Node(int value){
data=value;
next=NULL;
arb=NULL;
}
};
Now, I wrote the following code, but I am getting a segmentation fault runtime error. I can't find out what is causing this error.
Node *copyList(Node *head)
{
Node* ptr=head;
Node *temp;
Node *clonehead;
Node *clonetail;
while(ptr!=NULL){
temp=ptr->next;
Node* newnode=new Node(ptr->data);
if(ptr==head){
clonehead=newnode;
clonetail=clonehead;
}
else{
clonetail->next=newnode;
clonetail=newnode;
}
clonetail->arb=ptr->arb;
ptr->next=clonetail;
ptr=temp;
}
ptr=clonehead;
while(ptr!=NULL){
temp=ptr->arb;
ptr->arb=temp->next;
ptr=ptr->next;
}
return clonehead;
}
What is wrong with my code?
Link to the problem: Clone a linked list with next and random pointer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
