Reputation: 49
This is an interview question in "Cracking the coding interview". My code and test cases are here:
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
node* init(int a[], int n);
void remove(node* & c);
void printList(node* head);
int main()
{
int a[]={0,1,2,3,4,5,6,7,8,9};
node* testHead=init(a, 10);
printList(testHead);
cout<<endl;
int nth=9;
node *c=testHead;
for(int i=0; i<nth; i++)
{
c=c->next;
}
remove(c);
printList(testHead);
system("PAUSE");
return 0;
}
node* init(int a[], int n)
{
node *head, *p;
for(int i=0; i<n; i++)
{
node *nd=new node();
nd->data=a[i];
if(i==0)
{
head=nd;
p=nd;
}
else
{
p->next=nd;
p=nd;
}
}
return head;
}
void remove(node* & c)
{
if(c==NULL)
return;
node* tmp=c->next;
if(tmp==NULL)
{
delete c;
c=NULL;
}
else
{
c->data=tmp->data;
c->next=tmp->next;
delete tmp;
}
}
void printList(node* head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}
Here in the main function, I tried to delete the last node, with the data value 9. However, even in the function "remove", I checked the last node and if it is, I set it to NULL, the output will produce an error. Can anyone tell me why this happen?
Thanks.
Upvotes: 0
Views: 1956
Reputation: 12715
The problems are actually as follows:
Upvotes: 1
Reputation: 23
void remove(node* & c) // --> 1
{
if(c==NULL)
return;
node* tmp=c->next;
if(tmp==NULL)
{
delete c; // --> 2
c=NULL; // --> 3
}
else
{
c->data=tmp->data;
c->next=tmp->next;
delete tmp;
}
}
This is the thing:
//Check @WhozCraig comment for correction
delete
releases c
allocated memoryNULL
to c
Other word, how can you assign NULL
to a variable that has been released?
Upvotes: 0