Nix Nix - 2 months ago 13
C++ Question

How to search and insert multiple nodes in Linked List

I am trying to search for nodes, where the output i.e result of nodes is more than one. So i am trying to make a new doubly linked list and add those new nodes into it.
However only get 1 correct result, the second gives me I guess address or that node or is error. as shown in the image.

enter image description here

my code:

Order::Node* Order::searchByDate(string date) {
Node* cur = head;
Node* node = NULL;
cout << "\nSearching " << endl;
Sleep(400);

while (cur != NULL) {
if (cur->date == date) {
//create new node
Node* newNode = new Node;
newNode->prev = NULL;
newNode->next = cur;
//copy newNode to node(new linked list having all search result)
node = newNode;
node->prev = newNode;
node = newNode;
Sleep(400);
}

cur = cur->next;
}
return node;
}


Display function:

Node* cur = searchByDate(date);
while (cur != NULL) {
cout << cur->orderid << "\t\t" << cur->date << "\t" << cur->cust.custId << endl;
cur = cur->next;
}


Any solution that I can add all the searched nodes into one linked list.

Answer

The new node's

  • previous should the existing search results.
  • next should be null.

For the existing search results

  • next should point to the new node.

Keep another pointer to the start of the search results. Return this start node as the result of the method.

Try this

Order::Node* Order::searchByDate(string date) {
    Node* cur = head;
    Node* node = NULL;
    Node* start = NULL;

    while (cur != NULL) {
        if (cur->date == date) {

            //make a new node
            Node* newNode = new Node(cur->date);
            newNode->prev = NULL; //explicitly set to NULL
            newNode->next = NULL; //explicitly set to NULL

            if (node == NULL) {
                //very first node
                node = newNode;
                start = node;
            }
            else {
                //append new node to existing nodes
                //see diagram below
                node->next = newNode;
                newNode->prev = node;
                node = newNode;
            }
        }

        cur = cur->next;
    }
    return start;
}

append new node

Comments