# Linked List Jumps in C++

C++Server Side ProgrammingProgramming

Suppose we have a singly linked list node containing positive numbers. We have to find the same linked list where every node's next points to the node val nodes ahead. If we cannot find such node, next will be null.

So, if the input is like [2,3,10,5,9], then the output will be [2, 3, 15, ]

To solve this, we will follow these steps −

• Define an array v

• while node is not null, do −

• insert value of node into v

• node := next of node

• ret = new list node with value 0

• temp = ret

• i := 0

• while i < size of v, do −

• next of temp := new list node with value v[i]

• temp := next of temp

• i := i + v[i]

• return next of ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode {
public:
int val;
ListNode *next;
ListNode(int data) {
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v) {
for (int i = 1; i < v.size(); i++) {
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while (ptr) {
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* solve(ListNode* node) {
vector <int> v;
while(node){
v.push_back(node->val);
node = node->next;
}
ListNode* ret = new ListNode(0);
ListNode* temp = ret;
int i = 0;
while(i < v.size()){
temp->next = new ListNode(v[i]);
temp = temp->next;
i += v[i];
}
return ret->next;
}
};
main(){
Solution ob;
vector<int> v = {2,2,3,5,9,15,3,4};
}
{2,2,3,5,9,15,3,4}
[2, 3, 15, ]