This C Program prints the Nth node from the last node of a linked list. The approach used is to first point a pointer to a node which is N nodes ahead from the head. Then, move the Nth pointer and head pointer one node at a time till the Nth pointer has reached to the rear node. The pointer in the middle is the Nth pointer from the end.
Here is a source code of the C program to print the nth node from the last node of a linked list. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Print Nth Node from the last of a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void create(struct node **);
void nthnode(struct node *, int);
void release(struct node **);
int main()
{
struct node *p = NULL;
int n;
printf("Enter data into the list\n");
create(&p);
printf("Enter the value n to find nth position from the last node: ");
scanf("%d", &n);
nthnode(p, n);
release (&p);
return 0;
}
void nthnode(struct node *head, int n)
{
struct node *p, *q;
int i;
q = p = head;
for (i = 0; i < n && q != NULL; i++)
{
q = q->next;
}
if (i < n)
{
printf("Entered n = %d is larger than the number of elements = %d in list. Please try again.\n", n, i);
}
else
{
while (q->next != NULL)
{
q = q->next;
p = p->next;
}
printf("%d is %d nodes from the last node.\n", p->num, n);
}
}
void create(struct node **head)
{
int c, ch;
struct node *temp, *rear;
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
void release(struct node **head)
{
struct node *temp = *head;
*head = (*head)->next;
while ((*head) != NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}
$ cc nthnode.c $ ./a.out Enter data into the list Enter number: 1 Do you wish to continue [1/0]: 1 Enter number: 2 Do you wish to continue [1/0]: 1 Enter number: 3 Do you wish to continue [1/0]: 1 Enter number: 4 Do you wish to continue [1/0]: 1 Enter number: 5 Do you wish to continue [1/0]: 0 Enter the value n to find nth position from the last node: 2 3 is 2 nodes from the last node.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Design & Analysis of Algorithms MCQ
- Check Programming Books
- Practice Computer Science MCQs
- Practice Programming MCQs
- Check Data Structure Books