什么是链表反转
- 简单来说,链表反转就将原来的链表的循序倒置,头结点变成尾结点,第二个结点变成倒数第二个结点…
实现链表反转的方法
利用一个虚拟结点实现链表反转(源码常用,好理解)
-
示意图
-
源码加上理解注释
public static Node reverseList1(Node head){
if (head == null){
return null;//极端情况
}
//创建虚拟结点并指向头结点,虚拟结点是反转链表的头结点
Node ans = new Node(-1);
ans.next = head;
//创建一个用于遍历的结点,表示我们当前结点,初始为头结点
Node cur = head;
while(cur != null){
//由于后面是用头插法插入结点,那么cur.next肯定会变,先保存副本
Node next = cur.next;
//将当前遍历到的结点头插入反转链表
cur.next = ans.next;
ans = cur;
//再将cur指回来到原先该遍历到的结点
cur = next;
}
//返回去除了虚拟结点的反转链表的头结点
return ans.next;
}
直接操作链表实现链表反转(难一点,好考)
-
示例
-
源码
public static Node reverseList2(Node head){
if(head == null){
return null;
}
Node cur = head;
Node prev = null;
while(cur != null){
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}