我在尝试为我在C#中创建的LinkedList类编写反向递归方法时出现问题。 该链表中有两个指针之一的头,另一个用于尾部:在递归函数中颠倒链表c#
public class Node
{
public object data;
public Node next;
public Node(object Data)
{
this.data = Data;
}
}
public class LinkedList
{
Node head;
Node tail;
public void Add(Node n)
{
if (head == null)
{
head = n;
tail = head;
}
else
{
tail.next = n;
tail = tail.next;
}
}
现在,递归反向功能是这样的:
public void reverse_recursive()
{
Node temp_head = head;
if (temp_head == tail)
{
return;
}
while (temp_head != null)
{
if (temp_head.next == tail)
{
tail.next = temp_head;
tail = temp_head;
reverse_recursive();
}
temp_head = temp_head.next;
}
}
我有2个与烦恼它:首先是一个逻辑问题,我知道这个头在逆向后并不指向第一个节点。第二个问题是我可能对空指针做错了,所以程序崩溃了。
我也给你的主要程序:
class Program
{
static void Main(string[] args)
{
LinkedList L = new LinkedList();
L.Add(new Node("first"));
L.Add(new Node("second"));
L.Add(new Node("third"));
L.Add(new Node("forth"));
L.PrintNodes();
L.reverse_recursive();
L.PrintNodes();
Console.ReadLine();
}
}
谢谢你的帮助!
我可以问你为什么你还没有授予一个单一的问题? – varocarbas
在帮助我只想检查之前,你需要使用自己的链表类吗?有一个内置的类:http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx – Alden
您正在检查'(temp_head!= null)'在while中,但在temp_head中为 。如果(temp_head.next == tail)'可能会导致违规,那么next'可能是'null'。 – Thanushan