Saturday, 14 May 2011

Write a program to return the nth node from the end of a linked list.


#include "linkedlist.h"
#include

#define LL_LIMIT 10

/* Create LL */
NODE* createLL()
{
int index=0;
NODE* headNode = NULL;
while(index <= LL_LIMIT)
{
headNode = addAtHead(headNode, ++index);
}
return headNode;
}

/* get Nth Node from Last */
int getNthNodeLast(NODE* headNode, int nodeNum)
{
NODE* currentNode1 = headNode;
NODE* currentNode2 = headNode;
int count = 0;

while(currentNode1 != NULL)
{
count++;
currentNode1 = currentNode1->next;
if(count > nodeNum)
{
currentNode2 = currentNode2->next;
}
}

return currentNode2->data;
}

/* Driver program to test above functions */
int main()
{
NODE* headNode = NULL;
headNode = createLL();

displayAll(headNode);
printf("3rd Node is %d\n", getNthNodeLast(headNode, 3));
}

No comments:

Post a Comment