単独リンクリストを逆LeetCode206

免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
このリンク: https://blog.csdn.net/xiaoen1/article/details/102768576

単独リンクリストを逆LeetCode206

例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

高度:

あなたは、反復または再帰的にリストを逆にすることができます。次の2つの方法でこの問題を解決することはできますか?

イテレーション:

public ListNode reverseList(ListNode head) {
    ListNode cur = head;
    ListNode pre = null;
    ListNode tmp = null;
    while(cur!=null){
        tmp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = tmp;
    }
    return pre;
}

再帰:

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode nextNode = head.next;
    ListNode p = reverseList(nextNode);
    nextNode.next = head;
    head.next = null;
    return p;
}

おすすめ

転載: blog.csdn.net/xiaoen1/article/details/102768576
おすすめ