链表逆转递归方式:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode tou = new ListNode(0);
recursive(head,tou).next = null;
return tou.next;
}
private ListNode recursive(ListNode head,ListNode tou){
if(head.next==null||head==null){
tou.next=head;
return head;
}
if(head.next!=null){
ListNode ln = recursive(head.next,tou);
ln.next=head;
}
return head;
}
}
注意这里的返回的是tou.next,如果直接返回tou的话,或者在recursive函数中给tou赋值为head的话,得不到正确结果(引用也是值传递)
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return head;
ListNode p=head;
if(p.next==null){
return p;
}
else{
ListNode t=reverseList(p.next);
p.next.next=p;
p.next=null;
return t;
}
}
}
上面这种方法首先获取到尾节点,然后逐层返回该尾节点作为头节点,后面两条语句:p.next.next=p;和p.next一个是来做链表逆置的一个是用来断开原来的连接的
稍微有点复杂,但是画个图就明白了。