Get Second to Last Node in Linked List

Write a function that takes a linked list as input and returns the second to last node in the list.

Problem

Given a linked list, return the second to last node in the list.
Input: 1->2->3->4->5
Output: 4

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use two pointers, one that is one node ahead of the other.
// This way, when the first pointer reaches the end of the list, the second pointer will be at the second to last node.
// This solution is optimal because it only requires one pass through the list.

function secondToLast(list) {
  let first = list.head;
  let second = list.head;

  while (first.next) {
    first = first.next;
    second = second.next;
  }

  return second;
}

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The approach is also optimal, as it only requires one pass through the list.

Evaluated at: 2022-12-06 04:15:30