Horje
Give an algorithm for finding the ith-to-last node in a singly linked list in which the last node is indicated by a null next reference. Code Example
Give an algorithm for finding the ith-to-last node in a singly linked list in which the last node is indicated by a null next reference.
LinkedListNode nthToLast(LinkedListNode head, int n) {
  if (head == null || n < 1) {
    return null;
  }

  LinkedListNode p1 = head;
  LinkedListNode p2 = head;

  for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
    if (p2 == null) {
      return null; // not found since list size < n
    }
    p2 = p2.next;
  }

  while (p2.next != null) {
    p1 = p1.next;
    p2 = p2.next;
  }

  return p1;
}




Cpp

Related
Shell-Sort C++ Code Example Shell-Sort C++ Code Example
cout hex c++ Code Example cout hex c++ Code Example
bool to string arduino Code Example bool to string arduino Code Example
c++98 check if character is integer Code Example c++98 check if character is integer Code Example
c++ client service ros Code Example c++ client service ros Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
9