单向链表的反转,前提是有一个带头节点的单链表
反转过程中,cur 始终都是一个节点没变。
前两次的示意图如下,后边的操作都是一样的。
/**
* 链表反转 SimpleListWithHead 有头节点的链表
*/
public class ListReverse {
public static void main(String[] args) {
SimpleListWithHead<String> list = new SimpleListWithHead<>();
for (int i = 0 ; i < 6 ;i++){
list.add(String.valueOf(i));
}
System.out.println(list);
reverse(list);
System.out.println(list);
}
public static void reverse(SimpleListWithHead list){
Node head = list.getHeadNode();
Node current = head.next;
if (current == null){return;}
Node p;
while (current.next != null){
p = current.next;
current.next = p.next;
p.next = head.next;
head.next = p;
}
}
}
测试:
[0-> 1-> 2-> 3-> 4-> 5]
[5-> 4-> 3-> 2-> 1-> 0]