鏈表反轉(遞歸方式,非遞歸方式)


//非遞歸方式進行鏈表反轉
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