链表节点
package club.test;
/***
* 链表节点
* @author jiajia
*
*/
public class Node {
public int value;
public Node next;
public Node(int value, Node next) {
super();
this.value = value;
this.next = next;
}
}
算法实现
package club.test;
/***
* 反转一个链表,返回新链表的首节点
* @author jiajia
*
*/
public class TestMain2 {
public static void main(String[] args) {
Node list=new Node(1,new Node(3,new Node(5,null)));
//待反转链表
Node n=reversal(list);
//反转后链表的头节点
while(true) {
if(n!=null) {
System.out.print(n.value+" ");
n=n.next;
continue;
}
return;
}
}
/**
* 核心递归算法
* @param head 当前链表的头节点
* @return 返回新链表的头节点
*/
public static Node reversal(Node head) {
if(head==null||head.next==null) {
return head;
}else {
Node next=head.next;
head.next=null;
Node no=reversal(next);
next.next=head;
return no;
}
}
}
当前案例输出:5 3 1