实现逻辑为在遍历链表的时候,修改当前节点的指针域的指向,让其指向它的前驱节点。
反转方法如下:
internal class ArrayList
{
public static void Reverse(LNode<int> head)
{
//判断链表是否为空
if(head == null || head.next == null) return;
LNode<int> pre = null;//前驱节点
LNode<int> cur = null;//当前节点
LNode<int> next = null; //后继节点
//把链表首节点变为尾结点
cur = head.next;
next = cur.next;
cur.next = null;
pre = cur;
cur = next;
while (cur.next != null)
{
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
cur.next = pre;
head.next = cur;
}
}
public class LNode<T>
{
public LNode<T> next { get; set; }
public T data { get; set; }
}
测试代码如下:
static void TestArrayListReverse()
{
int i = 0;
LNode<int> head = new LNode<int>();
head.next = null;
LNode<int> tmp = null;
LNode<int> cur = head;
for (; i < 3; i++)
{
tmp = new LNode<int>();
tmp.data = i;
tmp.next = null;
cur.next = tmp;
cur = tmp;
}
ArrayList.Reverse(head);
}