【发布时间】:2016-06-10 19:47:28
【问题描述】:
如何反转链接节点...?
我只想制作一个反转链接节点的函数,函数的标题将是
public static Node<int> ReverseNode(Node<int> chain)
{
//...
}
例如。收到的节点是 [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;
}
你能告诉我我的代码有什么问题吗?
【问题讨论】:
-
你需要一个双链表而不是链表或者使用缓冲区来复制数据。
-
好吧,我有一门课,我只能用那门课……
-
这不是重复的......
-
@MohammedKhalaila 那到底怎么不是重复的?