反转链接节点
本文关键字:节点 链接 | 更新日期: 2023-09-27 18:36:34
如何反转链接的节点... ?
简单来说我想做一个反转链接节点的函数,函数的标题将是 public static Node<int> ReverseNode(Node<int> chain)
{
//...
}
例如。接收的节点是 [10->5->7]返回的节点应为 [7->5->10]
节点类在下面..
using System;
使用 System.Collections.Generic;使用系统文本;
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;
}
你能告诉我我的代码有什么问题吗?
这样的东西应该有效
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;
}
递归版本:
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;
}