Preview:
#include <iostream>

struct SinglyLinkedListNode {
    int data;
    SinglyLinkedListNode* next;
    SinglyLinkedListNode(int val) : data(val), next(nullptr) {}
};

int compare_lists(SinglyLinkedListNode* llist1, SinglyLinkedListNode* llist2) {
    while (llist1 != nullptr && llist2 != nullptr) {
        if (llist1->data != llist2->data) {
            return 0; // Lists are not equal
        }
        llist1 = llist1->next;
        llist2 = llist2->next;
    }
    
    // Check if both lists have reached the end
    if (llist1 == nullptr && llist2 == nullptr) {
        return 1; // Lists are equal
    } else {
        return 0; // One list is longer than the other
    }
}

int main() {
    int t;
    std::cin >> t; // Number of test cases
    while (t--) {
        int n1;
        std::cin >> n1; // Number of nodes in the first list
        SinglyLinkedListNode* llist1 = nullptr;
        SinglyLinkedListNode* tail1 = nullptr;
        
        for (int i = 0; i < n1; ++i) {
            int value;
            std::cin >> value;
            SinglyLinkedListNode* newNode = new SinglyLinkedListNode(value);
            if (llist1 == nullptr) {
                llist1 = newNode;
                tail1 = newNode;
            } else {
                tail1->next = newNode;
                tail1 = newNode;
            }
        }

        int n2;
        std::cin >> n2; // Number of nodes in the second list
        SinglyLinkedListNode* llist2 = nullptr;
        SinglyLinkedListNode* tail2 = nullptr;

        for (int i = 0; i < n2; ++i) {
            int value;
            std::cin >> value;
            SinglyLinkedListNode* newNode = new SinglyLinkedListNode(value);
            if (llist2 == nullptr) {
                llist2 = newNode;
                tail2 = newNode;
            } else {
                tail2->next = newNode;
                tail2 = newNode;
            }
        }

        std::cout << compare_lists(llist1, llist2) << std::endl;

        // Clean up memory (optional but good practice)
        // (You should implement a function to delete the linked list nodes)
    }

    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter