リンクされたリストのジャンプ


説明



正の整数を含む単一リンク リスト node が与えられます.すべてのノードの next がノード val 先のノードを指している同じリンクされたリストを返します.そのようなノードがない場合、next は null を指す必要があります.

制約:
  • n ≤ 100,000 nnode のノード数です

  • 例1



    入力




    node = [2, 1, 4, 1]
    


    出力




    [2, 4]
    


    説明




    Note that 2's next is 2 node ahead. 4's next is out of bounds, so it's set to null.
    



    直感



    実装




    import java.util.*;
    
    /**
     * class LLNode {
     *   int val;
     *   LLNode next;
     * }
     */
    class Solution {
        public LLNode solve(LLNode node) {
            int steps;
            LLNode head = node;
            while (node != null) {
                steps = node.val;
                for (int i = 1; i < steps; i++) {
                    if (node.next != null) {
                        node.next = node.next.next;
                    } else {
                        break;
                    }
                }
                node = node.next;
            }
            return head;
        }
    }
    


    複雑


  • 時間: O(n)
  • スペース: O(1)