leetcode记录 Reverse Linked List

链表逆转递归方式:
 /**
 * 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一个是来做链表逆置的一个是用来断开原来的连接的
稍微有点复杂,但是画个图就明白了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值