How to return Nth the node from the end of the linked list in one pass

Node * GetNthNode(Node * Head, int NthNode) {
  Node * pNthNode = NULL;
  Node * pTempNode = NULL;
  int nCurrentElement = 0;

  for (pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode -> pNext) {
    nCurrentElement++;
    if (nCurrentElement - NthNode == 0) {
      pNthNode = Head;
    } else
    if (nCurrentElement - NthNode > 0) {
      pNthNode = pNthNode -> pNext;
    }
  }
  if (pNthNode) {
    return pNthNode;
  } else
    return NULL;
}
Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in