static void Main(string[] args)
{
System.Console.WriteLine(Result());
System.Console.ReadLine();
}
//将单链表储存为数组,然后按照数组的索引逆序进行反转。但是,此方式比较浪费空间,而且需要两次遍历,效率不占优势
public static string Result()
{
Node node1=new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
node1.Next = node2;
node2.Next = node3;
node3.Next = node4;
node4.Next = node5;
Node orderNode=ConvertNodeIndex(node1);//通过node1对象就可以找到后面关联的4个对象
return GetNodeString(orderNode);
}
/// <summary>
/// 反转节点的索引
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static Node ConvertNodeIndex(Node node)
{
if (node == null)
return null;
List<Node> nodeList=new List<Node>();
while (node!=null)
{
nodeList.Add(node);
node = node.Next;//遍历为下1个赋值
}
for (int i = (nodeList.Count-1); i >= 0; i--)
{
Node changeIndexNode = nodeList[i];//获取当前节点从5>4>3>2>1的顺序
if (i == 0)
changeIndexNode.Next = null;
else
changeIndexNode.Next = nodeList[i - 1];//每个节点索引的下一个-1,向前反推
}
node = nodeList[nodeList.Count - 1];
return node;
}
/// <summary>
/// 将已排好序的节点返回String文本
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static string GetNodeString(Node node)
{
if (node == null)
return null;
StringBuilder sb=new StringBuilder();
Node temp = node;//临时节点
while (temp != null)
{
sb.Append(temp.Data);
temp = temp.Next;//每个当前节点=每个当前节点的下一节点
}
return sb.ToString();
}