编程面试中暴露的错误:链表
我正在阅读《编程面试暴露》一书。给出了用于在链接列表的前面插入元素的代码。
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
*head = newElem;
return true;
}
恕我直言,这段代码忘记更新新元素的下一个指针,不是吗?虽然我确信代码是错误的,但我只是想确认我的链表概念并没有严重错误。
我相信代码应该在正确的位置添加以下行。
newElem->next = *head;
有人可以告诉我我是对还是错吗?
I was going through the Programming Interviews Exposed book. There's a code given for inserting an element at the front of linked lists.
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
*head = newElem;
return true;
}
IMHO this code forgets to update the next pointer of the new element, doesn't it ? Although I am sure the code is wrong, I just want to confirm my linked list concepts are not horribly wrong.
I believe the code should add the following line at the right place.
newElem->next = *head;
Can someone please just tell me whether I am right or wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于这是插入在前面,所以你是对的。新节点的下一个应该是当前的头,然后头应该设置为指向新节点。
当然,这里还有其他一些不好的风格和设计,或者根本就是错误的。
Since this is inserting in the front, you're right. The new nodes's next should be the current head, then head should be set to point to the new node.
Of course, there are several other things here that are bad style and design, or just plain wrong.
我不确定你正在读什么样的面试书,但这个代码示例是糟糕的 C++。
是的,在覆盖
head
之前,您需要将newElem->next
指向旧的head
。另外,没有理由检查 newElem 是否为 NULL - 如果无法分配它,C++ 会抛出异常。另外,insertInFront
应该是IntElement
的成员函数,head
应该是数据成员。I'm not sure what kind of interview book you're reading, but this code example is terrible c++.
Yes, you need to point
newElem->next
to the oldhead
before overwritinghead
. Also, there's no reason to check if newElem is NULL - if it couldn't be allocated, C++ throws an exception. Also,insertInFront
should be a member function ofIntElement
, andhead
should be a data member.