一亩三分地论坛

 找回密码
 获取更多干货,去instant注册!

扫码关注一亩三分地公众号
查看: 624|回复: 1
收起左侧

[树/链表/图] confusing on an interview question

[复制链接] |试试Instant~ |关注本帖
尚佳蕾 发表于 2014-2-1 13:46:32 | 显示全部楼层 |阅读模式

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干货,去instant注册!

x
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.
hxtang 发表于 2014-2-3 09:53:17 | 显示全部楼层
The "next" member of the second last node in the list becomes a dangling pointer after the last node is removed. It should be updated to NULL after remove() is called.
回复 支持 反对

使用道具 举报

本版积分规则

请点这里访问我们的新网站:一亩三分地Instant.

Instant搜索更强大,不扣积分,内容组织的更好更整洁!目前仍在beta版本,努力完善中!反馈请点这里

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2016-12-10 21:27

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表