I started thinking about this before I saw all the other replies and came up with something. I used a recursive solution as Prelude hinted at, it was the only way I could think of to do it. Not entirely pleased with it but it does seem to work, at least for me:
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
int PrintNthFromEnd( struct node* ptrNode, int iNth )
{
int ret = 0;
if( ptrNode != NULL )
if( (ret = PrintNthFromEnd( ptrNode->next, iNth )) == (iNth+1) )
printf("%d value from end of list is %d.\n", iNth, ptrNode->data );
return ret+1
}
int main()
{
struct node *head, *curr;
/* List = 4 */
head = malloc(sizeof(struct node));
head->data = 4;
curr = head;
/* List = 4->9 */
curr->next = malloc(sizeof(struct node));
curr = curr->next;
curr->data = 9;
/* List = 4->9->14 */
curr->next = malloc(sizeof(struct node));
curr = curr->next;
curr->data = 14;
/* List = 4->9->14->15 */
curr->next = malloc(sizeof(struct node));
curr = curr->next;
curr->data = 15;
/* List = 4->9->14->15->19 */
curr->next = malloc(sizeof(struct node));
curr = curr->next;
curr->data = 19;
/* List = 4->9->14->15->19->21 */
curr->next = malloc(sizeof(struct node));
curr = curr->next;
curr->data = 21;
curr->next = NULL;
PrintNthFromEnd( head, 0 ); /* Should print 21 */
PrintNthFromEnd( head, 1 ); /* Should print 19 */
PrintNthFromEnd( head, 2 ); /* Should print 15 */
PrintNthFromEnd( head, 3 ); /* Should print 14 */
PrintNthFromEnd( head, 4 ); /* Should print 9 */
PrintNthFromEnd( head, 5 ); /* Should print 4 */
return 0;
}
I tested it on another machine so the code I typed here was transfered by looking at one computer and typing it on another so I may have made some typos during the transfer but on my test computer things seemed to work and it output:
Code:
0 value from end of list is 21.
1 value from end of list is 19.
2 value from end of list is 15.
3 value from end of list is 14.
4 value from end of list is 9.
5 value from end of list is 4.
[edit]Fixed some of my comments in the code. And yes I realize I didn't free the nodes.[/edit]