链表 1>2>3>4 反转之后:4>3>2>1
单链表的反转使用递归的思想就能轻松解决,使用递归完成反转,递归反转其实就是从原链表的第一个存数据的结点开始,依次递归调用反转每一个结点,直到把最后一个结点反转完毕,整个链表就反转完毕。
递归次数 | 当前节点 | 下一节点 | 操作 | 返回值 |
第一次 | 1 | 2 | Node(2).next = Node(1) Node(1).next = null | Node(1) |
第二次 | 2 | 3 | Node(3).next = Node(2) Node(2).next = null | Node(2) |
第三次 | 3 | 4 | Node(4).next = Node(3) Node(3).next = null | Node(3) |
第四次 | 4 | null | head.next = Node(4) | Node(4) |
public void reverse(){
if (isEmpty()){
return;
}
reverse(head.next);
}
public Node reverse(Node curr){
if (curr.next==null){
head.next=curr;
return curr;
}
Node pre = reverse(curr.next);
pre.next=curr;
curr.next=null;
return curr;
}