LeetCode - LinkedListの - 206。リバースリンクされたリスト(簡単)

206リバースリンクされたリスト(簡単)

トピックは対処https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

溶液

タイトルの意味は、リンクリストを反転させるために必要なリスト、および各反復と再帰を達成するための必要性を与えています。
解決策1:イテレーション

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode start = new ListNode(-1);
        ListNode p ,temp;
        while (head != null)
        {
            p = head.next;
            temp = start.next;
            start.next = head;
            head.next = temp;
            head = p;
        }
        return start.next;
    }
}

分析:リストの先頭と最初のノードの追加設定は、補間を取得します。
溶液II:再帰

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)  //链表为空或当前结点的下一个结点为空即返回head
            return head;
        ListNode p = reverseList(head.next);  //新链表的头结点
        head.next.next = head;                //将当前结点的下一个结点的下一个个结点置为head,即反转
        head.next = null;    //断掉head结点与下一个结点的连接
        return p;            //返回头结点
    }
}

分析:まず、次のノード又は現在のノードが空である、すなわちヘッドリターン空であるリストを決定下降またはリスト;再帰が、ヘッドノードは、新しいリストを返し、第1のノードがpに割り当てられた場合に、条件が満たされません、それは、pは、リンクリストのノードの新しいヘッドになります。この時点で、次のノードへの現在のノードの次のセット、すなわち、反転、ヘッドノードであり、その後、次のノードのヘッドノードとの接続を切断し、ヘッドノードpを返します。

参照
https://leetcode.com/problems/reverse-linked-list/solution/

ノート
ロジック1.再帰アルゴリズムは、本当にあまりにも慎重に精査したい非常に明確ではありません!

おすすめ

転載: www.cnblogs.com/victorxiao/p/11184521.html