gpt4 book ai didi

c++ - 如何将元素添加到链表的前面?

转载 作者:行者123 更新时间:2023-11-30 05:35:27 24 4
gpt4 key购买 nike

节点是这样设置的:

struct Node {
Node *next;
Node *prev;
T datum;
};

这是我的代码

    //MODIFIES: this
//EFFECTS: inserts i into the front of the list
void push_front(const T &datum)
{
Node newfirst = first; // set newnode to first
&first = &datum;
datum = newfirst;

}



Node *first; // points to first Node in list, or 0 if list is empty
Node *last; // points to last Node in list, or 0 if list is empty

出于某种原因,我认为这是不对的。

最佳答案

看来你需要以下内容

//this is my code
//MODIFIES: this
//EFFECTS: inserts i into the front of the list
void push_front(const T &datum)
{
first = new Node { first, nullptr, datum };

if ( !last ) last = first;
}

如果您的编译器不支持 operator new 的初始化列表,那么您可以这样写

//this is my code
//MODIFIES: this
//EFFECTS: inserts i into the front of the list
void push_front(const T &datum)
{
Node *tmp = new Node();

tmp->datum = datum;
tmp->next = first;

first = tmp;

if ( !last ) last = first;
}

关于c++ - 如何将元素添加到链表的前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33906400/

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