Teaching Kids Programming – Linked List Jumps via Recursion


Teaching Kids Programming: Videos on Data Structures and Algorithms

ou 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
Example 1
Input
node = [2, 1, 4, 1]

Output
[2, 4]

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

Linked List Jumps via Recursion

We can solve this one step at a time. We can find out the destination node from the current node with n jumps – and break when we reach the end. Then, we assign the next pointer of the current node to the destination node – which we can recursively jump.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# class LLNode:
#     def __init__(self, val, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def jump(self, node):
        if not node:
            return node
        
        head = node
        for _ in range(head.val):
            head = head.next
            if not head:
                break
        
        node.next = self.jump(head)
        return node
# class LLNode:
#     def __init__(self, val, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def jump(self, node):
        if not node:
            return node
        
        head = node
        for _ in range(head.val):
            head = head.next
            if not head:
                break
        
        node.next = self.jump(head)
        return node

See also: Recursive Algorithm to Compute the Linked List Jumps

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
334 words
Last Post: Teaching Kids Programming - Pairwise Linked List Nodes Swap Algorithm
Next Post: Teaching Kids Programming - Add Two Big Integers in Strings

The Permanent URL is: Teaching Kids Programming – Linked List Jumps via Recursion

Leave a Reply