namespace ShopEx.CRS.Test
{
/// <summary>
///将链表逆序
/// </summary>
public class ReverseLinkList
{
//入口
public static void Do()
{
//创建单链表
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Node head = new Node() { Num = array[0] };
Node tmp = head;
for (int i = 1; i < array.Length; i++)
{
Node newNode = new Node() { Num = array[i] };
tmp.Next = newNode;
tmp = tmp.Next;
}
//显示原链表
Console.WriteLine("原链表:" + DisplayLinkList(head));
//逆序
Node newHead = null;
Reverse_Recursive(head, head, ref newHead);
//显示逆序后的链表
Console.WriteLine("原链表:" + DisplayLinkList(newHead));
}
/// <summary>
/// 采用递归的方式
/// </summary>
/// <param name="cur">原链表头结点</param>
/// <param name="pre">当前节点的前驱节点</param>
/// <param name="tail">原链表的尾节点</param>
public static void Reverse_Recursive(Node cur, Node pre, ref Node tail)
{
if (cur == null) return;
//记录链表的尾节点
if (cur.Next == null)
{
tail = cur;
return;
}
//移动到下一个节点
pre = cur;
cur = cur.Next;
//对下一个节点继续递归调用
Reverse_Recursive(cur, pre, ref tail);
cur.Next = pre;
pre.Next = null;//这边防止原链表头结点与后驱节点形成环形链
}
public static string DisplayLinkList(Node head)
{
string linkListStr = string.Empty;
while (head!=null)
{
linkListStr += head.Num + ",";
head = head.Next;
}
return linkListStr;
}
public class Node
{
public int Num;
public Node Next;
}
}
}