如何将一个链接列表复制到另一个列表中?
我正在研究数据结构和链表,但我不了解如何制作链表副本的概念。有人可以解释一下,可能使用伪代码或 C 代码吗?
I'm studying data structures and linked lists, but I'm not getting the concept of how to make a copy of a linked list. Can someone explain this, possibly using pseudocode or C code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
复制链表的逻辑是递归的,并且基于以下观察:
如果用 C++ 对链表进行编码,这会非常干净:
The logic for duplicating a linked list is recursive and based on the following observations:
If you encode the linked list in C++, this can be very clean:
您了解如何向现有列表添加新节点吗?您了解如何遍历(即迭代)列表吗?复制列表只是同时执行这两个操作(遍历ListA;对于每个元素,复制该元素并将其作为新节点添加到ListB)。
Do you understand how to add a new node to an existing list? And do you understand how to traverse (i.e. iterate over) a list? Copying a list is just performing both of these operations simultaneously (traverse ListA; for each element, copy the element and add it as a new node to ListB).
这篇文章的答案已给出并被接受 - 一切都很好!
但是,如果有人正在C#中寻找迭代方法,这里是:
Node类:
这是迭代实现:
时间复杂度:O(n )
空间复杂度:O(n)
,其中 n = 链表中的节点数。
个人偏好使用递归或迭代方法,但是我建议在使用递归时考虑函数调用堆栈。
单元测试:
The answer to this post has been given and accepted - all good!
However, if someone is looking for an iterative approach in C#, here it is:
The Node class:
Here is the iterative implementation:
Time complexity: O(n)
Space complexity: O(n)
where n = number of nodes in the linked list.
Its personal preference to use recursive or iterative approach, however I would suggest to think about the function call stack when using recursive.
Unit test:
Java 版本的递归克隆解决方案。
伪代码:
程序[JAVA]:
Java version of the recursive clone solution.
Pseudocode :
Program [JAVA] :