Skip to main content

Find n/k-th Node in Linked List

Problem​

Given a singly linked list and a number k. Write a function to find the (N/k)th(N/k)^{th} element, where N is the number of elements in the list. We need to consider ceil value in case of decimals.

Input:​

The first line of input contains an integer T denoting the number of test cases. The first line of each test case consists of an integer N. The second line consists of N spaced integers.The last line consists of an integer k.

Output:​

Return the data value of (N/k)th node in the Linked List.

Your task:​

The task is to complete the function fractional_node() which should find the n/kth node in the linked list and return its data value.

Constraints:​

  • 1<=T<=1001 <= T <= 100
  • 1<=N<=1001 <= N <= 100
  • K>0K > 0

Solution​

Python​

def fractionalNodes(head,k):
if (k <= 0 or head == None):
return None
fractionalNode = None
i = 0
temp = head
while (temp != None):
if (i % k == 0):
if (fractionalNode == None):
fractionalNode = head
else:
fractionalNode = fractionalNode.next
i = i + 1
temp = temp.next
return fractionalNode.data

Java​

public static int nknode(Node head, int k) {
if (k <= 0 || head == null)
return -1;
Node fractionalNode = null;
int i = 0;
Node temp = head;
while (temp != null) {
if (i % k == 0) {
if (fractionalNode == null) {
fractionalNode = head;
} else {
fractionalNode = fractionalNode.next;
}
}
i++;
temp = temp.next;
}
if (fractionalNode != null) {
return fractionalNode.data;
}
else {
return -1;
}
}

C++​

int fractional_node(struct Node *head, int k) {
if (k <= 0 || head == nullptr)
return -1;
Node* fractionalNode = nullptr;
int i = 0;
Node* temp = head;
while (temp != nullptr) {
if (i % k == 0) {
if (fractionalNode == nullptr) {
fractionalNode = head;
} else {
fractionalNode = fractionalNode->next;
}
}
i++;
temp = temp->next;
}
if (fractionalNode != nullptr) {
return fractionalNode->data;
}
else {
return -1;
}
}

C​

int fractional_node(struct Node *head, int k) {
if (k <= 0 || head == NULL)
return -1;
struct Node *fractionalNode = NULL;
int i = 0;
struct Node *temp = head;
while (temp != NULL) {
if (i % k == 0) {
if (fractionalNode == NULL) {
fractionalNode = head;
} else {
fractionalNode = fractionalNode->next;
}
}
i++;
temp = temp->next;
}
if (fractionalNode != NULL) {
return fractionalNode->data;
}
else {
return -1;
}
}