public class LNode<T> //一次遍历原地反转
{
public T data;
public LNode<T> next;
//逆序算法01
public static void Reverse01(LNode<T> head)
{
//链表反转 保证至少有两个元素
//head==null 未初始化的链表
//head.next==null 仅包含头节点
//head.next.next==null 一个元素
if (head == null || head.next == null||head.next.next==null)
{
return;
}
LNode<T> pre;
LNode<T> cur;
LNode<T> next;
cur = head.next;
next = cur.next;
cur.next = null; //表首节点变为表尾节点
if (next.next == null) //只有两个元素的情况
{
head.next = next;
next.next = cur;
return;
}
while (next.next != null) //三个元素以上
{
pre = next.next;
next.next = cur;
cur = next;
next = pre;
}
head.next = next;
next.next = cur;
}
//递归逆序算法02
private static LNode<T> ReverseWithoutHead(LNode<T> firstNode)
{
//firstnode是第一个非head节点
if (firstNode == null || firstNode.next == null)
{
return firstNode;
}
else
{
LNode<T> newHead= ReverseWithoutHead(firstNode.next);
firstNode.next.next= firstNode;
firstNode.next = null;
return newHead;
}
}
public static void Reverse02(LNode<T> head)
{
if (head == null)
{
return;
}
LNode<T> newnode = ReverseWithoutHead(head.next);
head.next = newnode;
}
//插入算法03
public static void Reserve03(LNode<T> head)
{
//head不存储数据,保证有两个表项
if (head == null || head.next == null || head.next.next == null)
{
return;
}
else{
LNode<T> cur;
LNode<T> next;
cur = head.next.next;
head.next.next = null; //曾经的头节点指向null
while (cur != null)
{
next = cur.next;
cur.next = head.next;
head.next = cur;
cur = next;
}
}
}
}
测试:
static void Main(string[] args)
{
LNode<int> l05 = new LNode<int>() { data =5, next = null };
LNode<int> l04 = new LNode<int>() { data = 4, next = null };
LNode<int> l03 = new LNode<int>() { data = 3, next = null };
LNode<int> l02 = new LNode<int>() { data = 2, next = null };
LNode<int> l01 = new LNode<int>() { data = 1, next = null };
LNode<int> head = new LNode<int>() { data = 4399, next = null }; //头节点不存储数据,标记入口位置
head.next = l01;
l01.next = l02;
l02.next = l03;
l03.next = l04;
l04.next = l05;
Console.WriteLine($"order{head.next.data},{head.next.next.data},{head.next.next.next.data}," +
$"{head.next.next.next.next.data},{head.next.next.next.next.next.data}");
LNode<int>.Reserve03(head);
Console.WriteLine($"order{head.next.data},{head.next.next.data},{head.next.next.next.data}," +
$"{head.next.next.next.next.data},{head.next.next.next.next.next.data}");
Console.ReadKey();
}