链表反转(递归方式,非递归方式)


//非递归方式进行链表反转
public ListNode reverseList(ListNode head){
    if(head==null||head.next==null){
        return head;
    }else {
        ListNode pre=head;
        ListNode p=head.next;
        ListNode next=null;
        while (p!=null) {
            next=p.next;
            p.next=pre;
            pre=p;
            p=next;
        }
        head.next=null;
        return pre;
    }
}
//递归方式进行链表反转
public ListNode reverseListRecursive(ListNode head) {
    if(head==null||head.next==null){
        return head;
        
    }else{
        ListNode dot=recursive(head);
        head.next=null;
        return dot;
    }
}

public ListNode recursive(ListNode p){
    if(p.next==null){
        return p;
    }else{
        ListNode next=p.next;
        ListNode dot=recursive(next);
        next.next=p;
        return dot;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM