New Want to Write for Computaholics ? if Yes Contact us at "contact@computaholics.in"

C Program to Find Nth node from the end of a Linked List

Find Nth node from the end of a Linked List:-

1. Initailize Two Pointer p,q
2. First move 'p' pointer to n nodes from head.
3. Now move both pointers one by one until 'p' pointer reaches end. Now 'q' pointer will point to nth       node from the end. Return main pointer 'q'

#include<stdio.h>
#include<stdlib.h>

struct node{

int data;
struct node *next;
};

void insert(struct node **head,int new_data)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int TraverseFromLast(struct node *head,int Nth)
{
  struct node *p,*q;
  p=head;
  q=head;
  int x=1;

while(x!=Nth)
{
p=p->next;
x++;
}
while(p->next->next!=0)   //really not understand my logic p->next!=0 is correct but get answer by condition p->next->next!=0
{
p=p->next;
q=q->next;
}
printf("%d\n",q->data);
}

main()
{

struct node *head;
head=(struct node*)malloc(sizeof(struct node));

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);

int Nth;

printf("Nth element from last\n");
scanf("%d",&Nth);

TraverseFromLast(head,Nth);

}
Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics