增加一种递归法翻转单链表的方法:
package cn.lktbl;
import com.alibaba.fastjson.JSON;
public class ReversLinkTable {
public static void main(String[] args) {
Node n1 = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, new Node(6, null))))));
System.out.println(JSON.toJSON(n1));
System.out.println(JSON.toJSON(reverse(n1)));
}
private static Node reverse(Node node) {
if ((node == null) || (node.next == null)) {
return node;
}
Node head = reverse(node.next);
node.next.next = node;
node.next = null;
return head;
}
static class Node {
public int value;
public Node next;
public Node(int value, Node next) {
this.next = next;
this.value = value;
}
}
}
输出结果: