gpt4 book ai didi

c++ - 暴露的编程面试错误 : Linked Lists

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:22 25 4
gpt4 key购买 nike

我正在阅读《Programming Interviews Exposed》一书。有一个代码用于在链表的前面插入一个元素。

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

恕我直言,这段代码忘记更新新元素的下一个指针,不是吗?虽然我确定代码是错误的,但我只是想确认我的链表概念并没有大错特错。

我认为代码应该在正确的位置添加以下行。

newElem->next = *head;

谁能告诉我我是对还是错?

最佳答案

因为这是在前面插入,所以你是对的。新节点的next应该是当前的head,那么head应该指向新的节点。

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

当然,这里还有其他一些糟糕的风格和设计,或者完全错误。

关于c++ - 暴露的编程面试错误 : Linked Lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com