-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathN_by_KthNode_LL.java
More file actions
48 lines (43 loc) · 947 Bytes
/
N_by_KthNode_LL.java
File metadata and controls
48 lines (43 loc) · 947 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Node
{
int data;
Node next;
Node(int key)
{
data = key;
next = null;
}
}
*/
class GfG
{
public static int countNumberOfNodes(Node head) {
int counter = 0;
while (head != null) {
counter++;
head = head.next;
}
return counter;
}
public static int nknode(Node head, int k)
{
// add your code here
Node current = head;
int numberOfNodes = countNumberOfNodes(current);
current = head;
int position;
if ((numberOfNodes % k) == 0) {
position = numberOfNodes / k;
} else {
position = (numberOfNodes / k) + 1;
}
while (head != null && position > 1) {
position--;
current = current.next;
}
if (current == null) {
return -1;
}
return current.data;
}
}