# Find kth node from Middle towards Head of a Linked List in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In this problem, we are given a linked-list and a number k. Our task is to find kth node from Middle towards the Head of a Linked List.

Let’s take an example to understand the problem,

Input: linked-list : 4 -> 2 -> 7 -> 1 -> 9 -> 12 -> 8 -> 10 -> 5, k = 2

Output: 7

Explanation:

Middle node value is 9.

The 2nd node from middle towards head is 7.

## Solution Approach

We need to find kth element from the middle of the linked-list towards the beginning. For this we need to find the size of linked-list by traversing the linked-list from beginning to end and find size.

K element from the middle towards the start is the (n/2 + 1 - k)th element from the beginning.

## Example

Live Demo

#include <iostream>
using namespace std;

struct Node {
int data;
struct Node* next;
};

void pushNode(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
}

int findKmiddleNode(struct Node* head_ref, int k) {

int n = 0;
while (counter != NULL) {
n++;
counter = counter->next;
}
int reqNode = ((n / 2 + 1) - k);

if (reqNode <= 0)
return -1;

int count = 1;
while (current != NULL) {
if (count == reqNode)
return (current->data);
count++;
current = current->next;
}
}

int main()
{

int k = 2;
}
2th element from beginning towards head is 7