/** * 单链表逆反算法 * @author 15735400536 * */ public class LinkedTest { public static void main(String[] args) { Node head = new Node(0); Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); head.setNext(node1); node1.setNext(node2); node2.setNext(node3); /** * 打印正序单链表 */ Node next = head; while(null != next) { System.out.print(next.getData() + " => "); next = next.getNext(); } head = reversal(head); System.out.println(" *****************************"); while(null != head) { System.out.print(head.getData() + " => "); head = head.getNext(); } } /** * 单向链表节点反转方法 * @param node * @return * 描述:1. 先判断该链表是否只有node一个节点,是,返回节点 * 2.否,递归 reversal()方法,返回最后一个节点,即逆向链表的head */ public static Node reversal(Node node) { //System.out.println(" " +node.getData() + " => " + node.getNext()); /** * 先判断该节点是为单节点 */ if(null == node || null == node.getNext()) { return node; } //逆向链表head => 3 Node newNode = reversal(node.getNext()); //获得下一个节点,设置下一个节点的下一个节点为前一个节点 node.getNext().setNext(node); node.setNext(null); return newNode; } } class Node { /** * 该节点存储的数据 */ private Object data; /** * 下一个节点 */ private Node next; public Object getData() { return data; } public Node getNext() { return next; } public void setData(Object data) { this.data = data; } public void setNext(Node next) { this.next = next; } public Node(Object data) { this.data = data; } }