Thursday, June 24, 2021
Home coding Write a program to to find nth node from end of linkedlist.

Write a program to to find nth node from end of linkedlist.

Given a linkedlist, we have to find the nth node of linkedlist from the end.

Example:

Input:1 2 3 4 5 6 7   k=2
Output:6

Logic:

STEP 1:start traversing the linkedlist till reach the end of linkedlist.
STEP 2:find the length of linkedlist.
STEP 3:k=length-nth node of linkedlist.
STEP 4:again start traversing linkedlist,till kth node and print it.

Code

int NthNodeLinkedlist(Node *head,int k)
{
    if(head==NULL)
    {
        return;
    }
    int count=0;
    Node *temp=head;
    while(head!=NULL)
    {
        count++;
        head=head->next;
       
    }
    int p=count-k+1;
    int i=0;
    while(temp!=NULL && i<p)
    {
        i++;
        temp=temp->next;
    }
  
return temp->data;
}

Ouput:

1 2 3 4 5 6 7 
k=2

output:
6

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments