翻轉鏈表的遞歸和非遞歸

輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        //遞歸
        /*
        if(head==null || head.next==null)
            return head;
        ListNode p=ReverseList(head.next);
        head.next.next=head;
        head.next=null;
        return p;
        */

        //注意判斷是否爲空鏈表,以及是否只有一個元素的情況

        if(head==null)
            return null;
        ListNode p=head;
        ListNode q=p.next;
        if(q==null)
            return p;
        ListNode r=q.next;
        head.next=null;
        q.next=p;
        while(r!=null){
            p=q;
            q=r;
            r=r.next;
            q.next=p;
        }
        return q;


    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章