使用和不使用递归来反转单链表
我是数据结构的新手,我知道这是一个很常见的问题。但我知道 .NET 中的 LinkedList 是双向链接的,那么我将如何在 C# 中为单链表编写代码。
有人可以写一下示例代码吗?
I am new to data structures, and I know this is a very common question to ask. But I know LinkedList in .NET is doubly-linked, so how I will write code for a singly-linked list in C#.
Could someone please write sample code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这里就用到了递归。
Here it is using recursion.
使用循环(当前元素:currentNode,在循环外初始化的变量:previousNode,nextNode)
Use loop (current element: currentNode, variables initialzied outside loop: previousNode, nextNode)
由于这可能是家庭作业,因此我将以一种可能非常令人困惑的方式来陈述这一点,以免完成所有工作。希望我的尝试不会让事情变得更加混乱(这是很有可能的)。
当您拥有对列表中节点(例如第一个节点)的引用时,您还拥有对其后面的节点的引用。您只需使以下节点引用当前节点,同时保留有关以下节点(及其先前状态)的足够信息即可为其执行类似的工作。现在唯一棘手的部分是处理边界条件(列表的开头和结尾)。
Since this is likely homework, I'm going to state this in a way that might be pretty confusing so as not to do all the work. Hopefully my attempt doesn't just make things more confusing (which is highly possible).
When you have a reference to a node in the list (say the first node), you also have a reference to the node that follows it. You just need to make the following node refer to your current node while keeping enough information around about the following node (and its previous state) to perform similar work for it. Now the only tricky parts are dealing with the boundary conditions (the start and the end of the list).
这是 .net (C#) 中链接的反转迭代和递归
(请注意,链表同时维护第一个和最后一个指针,以便我可以在 O(1) 中追加到末尾或在头部插入 - 不必这样做。我只是按上面定义了我的链表行为)
<递归:
Here is linked reversal iterative and recursive in .net (C#)
(note the linked list is maintaining both first and last pointers so that i can append at the end or insert at head in O(1) - one doesn't have to do this. I just defined my linked list behavior as above)
Recursive:
您需要定义一个节点数据结构,其中包含一些数据和对链表中下一个节点的引用。类似于:
然后您可以编写一个算法以相反的顺序循环列表,构造一个新的反向列表。
You need to define a node data structure which contains some data and a reference to the next node in the linked list. Something like:
Then you can write an algorithm to loop over the list in reverse order, constructing a new reversed list.