Untitled

 avatar
unknown
plain_text
25 days ago
1.1 kB
7
Indexable
#include <iostream>
using namespace std;

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

Node* build(int n) {
    Node* head = NULL;
    Node* temp = NULL;
    for (int i = 1; i <= n; i++) {
        Node* p = new Node;
        p->value = i * 10;
        p->next = NULL;
        if (head == NULL) {
            head = p;
            temp = p;
        } else {
            temp->next = p;
            temp = p;
        }
    }
    return head;
}
// my solution function tested on 10 different test cases.
int midval(Node* head) {
    int count = 0;
    Node* temp = head;
    Node* mid = head;

    while (temp->next != NULL) {
        count++;
        temp = temp->next;
        if (count % 2)
            continue;
        else
            mid = mid->next;
    }

    return (mid->value);
}

int main() {
    for (int n = 1; n <= 10; n++) {
        Node* head = build(n);
        cout << "n=" << n << " | list: ";
        Node* t = head;
        while (t != NULL) {
            cout << t->value;
            if (t->next) cout << "->";
            t = t->next;
        }
        cout << " | midval=" << midval(head) << endl;
    }

    return 0;
}
Editor is loading...
Leave a Comment