less than 1 minute read

You are given a singly linked list node containing positive integers. Return the same linked list where every node’s next points to the node val nodes ahead. If there’s no such node, next should point to null.

Constraints

  • n ≤ 100,000 where n is the number of nodes in node

https://binarysearch.com/problems/Linked-List-Jumps

ExamplesPermalink

Example 1Permalink

Input

  • node =
example1Node 0 2 1 1 0->1 2 4 1->2 3 1 2->3

Output

  • answer =
example1Output 0 2 1 4 0->1

Explanation

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

SolutionPermalink

/**
* class LLNode {
* public:
* int val;
* LLNode *next;
* };
*/
LLNode *solve(LLNode *node)
{
// keep this for final ans
LLNode *res = node;
while (node)
{ // repeat
LLNode *curr = node;
// jump "step" amount of times
for (int i = node->val; i > 0 && node; i--)
{
node = node->next;
}
// assign
curr->next = node;
}
return res;
}

Leave a comment