Search
 
SCRIPT & CODE EXAMPLE
 

CPP

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;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: convert char to int c++ 
Cpp :: find a number in vector c++ 
Cpp :: c++ range based for loop 
Cpp :: for loop in cpp 
Cpp :: char to string c++ 
Cpp :: c++ get last element in vector 
Cpp :: C++ :: 
Cpp :: Subarray with given sum in c++ 
Cpp :: c++ changing string to double 
Cpp :: inheritance example in C plus plus 
Cpp :: run c++ program mac 
Cpp :: c++ recursion 
Cpp :: c++ find index of all occurrences in string 
Cpp :: walk filesystem in c++ 
Cpp :: how to copy vector to another vector in c++ 
Cpp :: disallowcopy c++ 
Cpp :: C++ linked list iterator 
Cpp :: cmake g++ address sanitizer 
Cpp :: string in c++ 
Cpp :: opencv compile c++ 
Cpp :: Basic Input / Output in C++ 
Cpp :: inline function in cpp 
Cpp :: pow without math.h 
Cpp :: what is the time complexitry of std::sort 
Cpp :: Maximum sum of non consecutive elements 
Cpp :: definition of singly linkedlist 
Cpp :: c++ power of two 
Cpp :: c++ char 
Cpp :: problem category codechef solution in c++ 
Cpp :: C++ Vector Initialization method 03 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =