翻转链表:
Node类:
public class Node {
private int value;
private Node next;
}
需求:
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
//TODO 翻转链表
NodeUtils.reverseNodes(Params);
}
这里我们使用一个递归调用:
public class NodeUtils {
public static void reverseNodes(Node node, Node next){
reverseNode(node, next);
node.setNext(null);
}
private static void reverseNode(Node node, Node next){
if (node != null && next != null){
Node nextNext = next.getNext();
next.setNext(node);
reverseNode(next, nextNext);
}
}
}