编程面试中暴露的错误:链表

发布于 2024-09-27 17:02:10 字数 438 浏览 1 评论 0原文

我正在阅读《编程面试暴露》一书。给出了用于在链接列表的前面插入元素的代码。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

土豪我们做朋友吧 2024-10-04 17:02:10

由于这是插入在前面,所以你是对的。新节点的下一个应该是当前的头,然后头应该设置为指向新节点。

bool insertInFront( IntElement **head, int data ){
    IntElement *newElem = new IntElement;
    if( !newElem ) return false;
    newElem->data = data;
    newElem->next = *head;
    *head = newElem;
    return true;
}

当然,这里还有其他一些不好的风格和设计,或者根本就是错误的。

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.

bool insertInFront( IntElement **head, int data ){
    IntElement *newElem = new IntElement;
    if( !newElem ) return false;
    newElem->data = data;
    newElem->next = *head;
    *head = newElem;
    return true;
}

Of course, there are several other things here that are bad style and design, or just plain wrong.

淡淡の花香 2024-10-04 17:02:10

我不确定你正在读什么样的面试书,但这个代码示例是糟糕的 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 old head before overwriting head. 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 of IntElement, and head should be a data member.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文