Search code examples
c++linked-listdynamic-memory-allocationsingly-linked-listfunction-definition

C++ Linked List find() sharing nodes between two linked list


I have two structs Invoice & InvoiceDetails defined as follow:

struct InvoiceDetails {
    int invoiceId;
    int productId;
    int price;
    int quantity;
};

struct Invoice {
    int id;
    int createdAt;
};

And a Linked List for the data structure:

template<typename T>
struct Node {
    T data;
    Node *next;
};

template <typename T>
struct List {
    Node<T> *head = NULL;
    Node<T> *tail = NULL;
};

I need a method like "find All InvoiceDetails by invoiceId", and came up with the following:

template <typename T>
void add(List<T> &list, Node<T> *p) {
    if (list.head == NULL) {
        list.head = p;
        list.tail = list.head;
    } else {
        list.tail->next = p;
        list.tail = p;
    }
}

List<InvoiceDetails> findByInvoiceId(const List<InvoiceDetails> &list, int invoiceId) {
    List<InvoiceDetails> result;    
    Node<InvoiceDetails> *current = list.head;
    while (current != NULL) {
        if (current->data.invoiceId == invoiceId) {
            add(result, current);
        }
        current = current->next;
    }

    return result; 
}

I have the problem at runtime which is described in the image below (All the data in the txt files are exactly the same as the data model):

image

You could see the problem that the item on Invoice2 would also appear on Invoice1, which is not true!


Solution

  • The data member next of the node pointed to by the pointer current that is added to the new list is not set to nullptr.

    First of all, either you need to create a dynamic copy of the node pointed to by the pointer current that is added to the new list, and set its data member next to nullptr.

    Or, you need to remove from the source list the node that is added to the new list, also setting its data member next to nullptr.