反转链表

//思路一:
//使用指针
public ListNode ReverseList(ListNode head) {
    if(head==null || head.next==null){
        return head;
    }

    ListNode pre=null;
    ListNode cur=head;

    while(cur!=null){
        ListNode next = cur.next;

        cur.next = pre;
        pre=cur;
        cur=next;
    }
    return pre;
}
//思路二:
//使用递归
public ListNode ReverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }

        //tail 是 head.next 链表反转后的最后一个结点 
        ListNode tail = head.next;
        
        //反转 head.next 链表
        ListNode next = ReverseList(head.next);
        
        head.next = null; //注意:十分重要:head.next 链表反转后,未反转的只有 head 一个结点
        tail.next = head;
        return next;
    }

https://www.mianshi.onlinehttps://www.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!

逃跑的眼镜_bvbEK5
7 声望0 粉丝