首页 > 其他 > 详细

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

时间:2016-12-03 01:27:32      阅读:144      评论:0      收藏:0      [点我收藏+]
//非递归方式进行链表反转
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;
    }
}

 

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

原文:http://www.cnblogs.com/fanfengzi/p/6127781.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!