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) {
   ListNode *head = new ListNode(v[0]);
   for (int i = 1; i < v.size(); i++) {
      ListNode *ptr = head;
      while (ptr->next != NULL) {
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head) {
   ListNode *ptr = head;
   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};
   ListNode *head = make_list(v);
   print_list(ob.solve(head));
}

Input

{2,2,3,5,9,15,3,4}

Output

[2, 3, 15, ]
raja
Published on 02-Sep-2020 12:17:27
Advertisements