gpt4 book ai didi

c++ - 包含节点 C++ 的简单单链表的复制构造函数

转载 作者:行者123 更新时间:2023-11-30 01:29:28 24 4
gpt4 key购买 nike

我不是很擅长这个,而且我有点难以为单个链表和随之而来的节点制作复制构造函数。

这是我的头文件:

#pragma once

#include <iostream>
using namespace std;

class Node
{
public:
int data;
Node* next;
Node()
{
next = NULL;
data = 0;
}
Node(const Node& copyNode); /*: data(copyNode.data), next(copyNode.next ? new Node(*copyNode.next) : NULL)*/

};

class SLLIntStorage
{
public:
Node* head;
Node* current;
Node* tail;

void Read(istream&);
void Write(ostream&);
void setReadSort(bool);
void sortOwn();
void print();

void mergeSort(Node**);
Node *merge(Node*, Node*);
void split(Node*, Node**, Node**);

bool _sortRead;
int numberOfInts;

SLLIntStorage(const SLLIntStorage& copying) //: head(copying.head ? new Node(*copying.head) : NULL)
{

}

SLLIntStorage(void);
~SLLIntStorage(void);
};

inline ostream& operator<< (ostream& out, SLLIntStorage& n)
{
n.Write(out);
return out;
}
inline istream& operator>> (istream& in, SLLIntStorage& s)
{
s.Read(in);
return in;
}

任何人都可以帮助我了解它的工作原理以及我可以做些什么来创建它吗?谢谢。

最佳答案

要复制链表,您必须遍历整个链表并复制每个节点,并将其附加到新链表中。请记住,您不仅要复制指针,还必须复制整个 Node 结构以及任何需要复制的数据(例如,如果数据是指针,则需要进行深度复制那些也是)。

所以这是您的 SLLIntStorage 类的示例复制构造函数:

SLLIntStorage(const SLLIntStorage& copying) : head(NULL)
{
Node* cur = copying.head;
Node* end = NULL;

while (cur)
{
Node* n = new Node;
n->data = cur->data;

if (!head) {
head = n;
end = head;
} else {
end->next = n;
end = n;
}

cur = cur->next;
}
}

请注意,我没有考虑 tailcurrent 数据成员等。您必须考虑这些。

关于c++ - 包含节点 C++ 的简单单链表的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5852624/

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