Find the fractional (or n/k – th) node in linked list in C++


Suppose we have a singly linked list and the number k. We have to write a function to find the (n/k)th element, where n is the number of elements in the list. For decimals, we will choose the ceiling values. So if the list is like 1, 2, 3, 4, 5, 6, and k = 2, then output will be 3, as n = 6 and k = 2, then we will print n/k th node so 6/2 th node = 3rd node that is 3.

To solve this we have to follow some steps like below −

  • Take two pointers called temp, and fracPoint, then initialize them with null and start respectively.
  • For every k, jumps of the temp pointer, make one jump of the fracPoint pointer.

Example

 Live Demo

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node* next;
};
Node* getNode(int data) {
   Node* new_node = new Node;
   new_node->data = data;
   new_node->next = NULL;
   return new_node;
}
Node* fractionalNodes(Node* start, int k) {
   if (k <= 0 || start == NULL)
      return NULL;
   Node* fracPoint = NULL;
   int i = 0;
   for (Node* temp = start; temp != NULL; temp = temp->next) {
      if (i % k == 0) {
         if (fracPoint == NULL)
            fracPoint = start;
         else
            fracPoint = fracPoint->next;
      }
      i++;
   }
   return fracPoint;
}
void printList(Node* node) {
   while (node != NULL) {
      cout << node->data << " ";
      node = node->next;
   }
   cout << endl;
}
int main(void) {
   Node* start = getNode(1);
   start->next = getNode(2);
   start->next->next = getNode(3);
   start->next->next->next = getNode(4);
   start->next->next->next->next = getNode(5);
   int k = 2;
   cout << "List is: ";
   printList(start);
   Node* answer = fractionalNodes(start, k);
   cout << "\nFractional node is " << answer->data;
}

Output

List is: 1 2 3 4 5
Fractional node is 3

Updated on: 19-Dec-2019

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements