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

//非递归方式进行链表反转
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;
    }
}

 

posted @ 2016-12-02 23:58  帆疯子  阅读(1640)  评论(1编辑  收藏  举报