copyRev
void copyRev(node *head1, node *&head2)
{
stack<int> dat;
node* curr = head1;
while(curr!=NULL){
dat.push(curr->data);
curr = curr->next;
}
while(!dat.empty()){
append(head2,dat.top());
dat.pop();
}
}
append
void append(node* &head, int data){
if(head==NULL){
head= new node;
head->data = data;
head->next = NULL;
}
else{
node *curr = head;
while((curr)->next!=NULL){
(curr) = (curr)->next;
}
(curr)->next = new node;
(curr) = (curr)->next;
(curr)->data = data;
(curr)->next = NULL;
}
}
Well, I’m trying to clone the reverse of a linked list. I know how to reverse a list in place. But this code gives me a Bus error(code dumped).
This is how I call the function in main()
node *head;
for(int i = 0;i<9;i++){
append(head,i*i);
}
node *revHead;
printList(head);
copyRev(head,revHead);
printList(revHead);
in append() function, I check for NULL head and create a new node if it is NULL. moreover, the append function properly adds the elements to the list. The problem arose only after I called the copyRev procedure.
I have tried in-place reversing and it works. I need to clone the reverse of a linked list. Both Iterative and Recursive solutions are welcome. Also please point out the error in the above code.
This is my own practice problem but not a homework problem
You are not initializing your pointers:
As a result they have indeterminate values (ie they are random).
Using the values in these poitners in any way is undefined behavior. Which can be your error.
Just initialize them:
Recursive reverse of a linked list in place: