如何反转链接节点??
我想创建一个反转链接节点的函数,该函数的标题将是
public static Node<int> ReverseNode(Node<int> chain)
{
//...
}
对于Ex。接收节点是[10-> 5-> 7] 返回的节点应该是[7-> 5-> 10]
节点类是下面..
using System;
使用System.Collections.Generic; 使用System.Text;
public class Node<T>
{
private T info;
private Node<T> next;
public Node(T x)
{
this.info = x;
this.next = null;
}
public Node(T x, Node<T> next)
{
this.info = x;
this.next = next;
}
public T GetInfo()
{
return (this.info);
}
public void SetInfo(T x)
{
this.info = x;
}
public Node<T> GetNext()
{
return (this.next);
}
public void SetNext(Node<T> next)
{
this.next = next;
}
public override string ToString()
{
return ("" + this.info + "-->");
}
}
尝试这样做,但由于某种原因它没有工作......为什么?
public Node<T> reverse()
{
Node<T> chain1 = data.GetFirst();
Node<T> chain2 = new Node<T>(chain1.GetInfo());
Node<T> p = chain1.GetNext() ;
while (p != null)
{
Node <T> Tmp = p.GetNext();
p.SetNext(chain2);
chain2 = p;
p = Tmp;
}
Console.WriteLine( chain2.ToString());
return chain2;
}
您能否告诉我我的代码有什么问题?
答案 0 :(得分:0)
这样的事情应该有效
static Node<int> ReverseNode(Node<int> chain)
{
Node<int> lastNode = new Node<int>(chain.GetInfo());
Node<int> currentNode = chain.GetNext();
while(currentNode != null)
{
Node<int> nextNode = new Node<int>(currentNode.GetInfo(),lastNode);
lastNode = nextNode;
currentNode = currentNode.GetNext();
}
return lastNode;
}
答案 1 :(得分:0)
递归版:
public static Node<int> ReverseNode(Node<int> chain)
{
if (chain.GetNext() == null)
return chain;
var reversedChain = ReverseNode(chain.GetNext());
chain.GetNext().SetNext(chain);
chain.SetNext(null);
return reversedChain;
}