安全プランを証明する:リバースリスト(再帰的に、leetcode206)

トピック:

 

リストを反転リストを入力した後、出力ヘッダの新しいリスト。

回答:

解決策1:

事前入金を使用する前に、次のように最初のアイデアは、次の後の沈殿物のいずれかです。

/*
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 pre = null;
        ListNode next = null;
        while(head!=null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

対処方法2:

再帰的には、次の通り:

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode node = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }
}

 

公開された92元の記事 ウォンの賞賛2 ビュー8414

おすすめ

転載: blog.csdn.net/wyplj2015/article/details/104862973
おすすめ