public class Node
{
public Node(int val)
{
Val = val;
}
public Node Next { get; set; }
public int Val { get; }
}
下面是迭代实现:
public Node CopyLinkedListIteratively(Node head)
{
// validation:
if (head == null) return null;
// current node is always a 'new' node with value.
Node currentNode = new Node(head.Val);
// set copyList and previous to current node to start with - which is true at this point in time!
Node copyList = currentNode;
Node previous = currentNode;
// move head one step forward as we already have copied its value.
head = head.Next;
// keep moving until we hit a null reference which is the end.
while (head != null)
{
currentNode = new Node(head.Val); // create a new node every time as we move forward.
previous.Next = currentNode; // set previous node's next to current node as previous node itself is one step behind the current.
previous = previous.Next; // move prev pointer forward
head = head.Next; // move head pointer forward as well
}
// return the reference to copyList.
// copyList and previous both started off pointing to the currentNode, then in the while loop
// previous kept moving forward till all nodes are copied.
// copyList reference never moved from its position so its still pointing at the start.
return copyList;
}
[Test]
public void CopyLinkedListIterativelyTest()
{
Node head = new Node(1);
head.Next = new Node(2);
head.Next.Next = new Node(3);
head.Next.Next.Next = new Node(4);
head.Next.Next.Next.Next = new Node(5);
var actual = runner.CopyLinkedListIteratively(head);
while (actual != null)
{
Assert.AreEqual(head.Val, actual.Val);
actual = actual.Next;
head = head.Next;
}
}
4条答案
按热度按时间k4aesqcs1#
复制链表的逻辑是递归的,并且基于以下观察:
1.空列表的克隆就是空列表。
1.具有第一个节点x和剩余节点xs的列表的克隆是x的副本前置到xs的克隆。
如果你在C++中编码链表,这可能是非常干净的:
7bsow1i62#
您了解如何向现有列表中添加新节点吗?“你知道怎么做吗?即迭代)列表?复制一个列表就是同时执行这两个操作(遍历ListA;对于每个元素,复制该元素并将其作为新节点添加到列表B)。
2w2cym1i3#
这篇文章的答案已经给出并被接受了--一切都很好!然而,如果有人正在寻找**C#**中的迭代方法,那么它就是:
Node类:
下面是迭代实现:
时间复杂度:O(n)
空间复杂度:O(n)
其中n =链表中的节点数。
我个人倾向于使用递归或迭代方法,但是我建议在使用递归时考虑函数调用堆栈。
单元测试:
balp4ylt4#
Java版本的递归克隆解决方案。
伪代码:
1.每个节点都是一个新初始化的节点
1.递归调用clone函数为每个节点创建一个新节点
程序[JAVA]: