
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Linked List Jumps in C++
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
#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, ]
Advertisements