链表反转的三种方法
- 普通链表反转法
- 思想:借助三个Node变量进行节点的移动,促成next指向变化,从而使链表反转
- 递归链表反转法
- 思想:想像一个反转成功的链表与剩下的头节点的反转,思考如何进行,只要拆分出来的相似问题解决好了,就直接可用调用自己的方法进行解决
- 头节点链表反转法
- 借助头节点以及新节点(newNode=null),这里是一个循环,条件为头不为空,第一步保存头节点为temp,第二步头节点指向它的下一个节点,保存好的头节点的下一个节点指向新节点(此时反转成功,再把newNode后移就行)
package com.javase.reverselink;
public class ReverseLink {
public static void main(String[] args) {
Node<Integer> head =buildLink();
Node<Integer> newNode =recursiveReverseLink(head);
print(newNode);
}
public static Node<Integer> reverseLink(Node<Integer> head){
//提前判断,如果链表的长度为0或1,则不需要反转
if(head==null||head.next==null)