Find the Middle Node in a Singly Linked List

Given a singly linked list, this function returns the middle node of the list. If the list has an even number of nodes, the function returns the node at the start of the second half of the list.

Problem

Given a singly linked list, write a function that returns the middle node of the list. If the list has an even number of nodes, the function should return the node at the start of the second half of the list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6
Output: 4

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

struct Node {
    int data;
    Node* next;
};

Node* createNode(int data) {
    Node* node = new Node;
    node->data = data;
    node->next = NULL;
    return node;
}

Node* createList(vector<int> data) {
    Node* head = createNode(data[0]);
    Node* current = head;
    for (int i = 1; i < data.size(); i++) {
        current->next = createNode(data[i]);
        current = current->next;
    }
    return head;
}

void printList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        cout << current->data << " ";
        current = current->next;
    }
    cout << endl;
}

Node* getMiddleNode(Node* head) {
    Node* slow = head;
    Node* fast = head; while (fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

int main() {
    vector<int> data = {1, 2, 3, 4, 5, 6};
    Node* head = createList(data);
    printList(head);
    Node* middle = getMiddleNode(head);
    cout << middle->data << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate's approach is to create a linked list from the given vector data, print the list, and then find the middle node of the list.

Evaluated at: 2022-12-05 10:15:46