Home > front end >  How do you write a function that returns a node which value corresponds to a value stored in a varia
How do you write a function that returns a node which value corresponds to a value stored in a varia

Time:11-26

I stumbled across this question in an old textbook I bought ages ago, whilst strictly speaking it is not too difficult, I could not find a post here that simply answered this one question. As such I thought "Hey perhaps someone starting out might be confused about this", and so I put together the following code:

#include <iostream>

using namespace std;

// Structures
struct charNode {
    char Node;
    charNode *next;
};

// Functions
charNode* getCharNode(char c) {
    return ; //<----- Return Node Here 
}

CodePudding user response:

What this needs is to be put in a class or else you must have a global variable that points to the head of that singly linked list.

An example class could look like this:

#include <iostream>

class singly_linked_list {
    struct charNode {
        char Node;
        charNode *next;
    };

public:
    // find the charNode with the value `c`:
    charNode* getCharNode(char c) {
        for(charNode* curr = head; curr != nullptr; curr = curr->next) {
            if(curr->Node == c) return curr;
        }
        return nullptr;
    }

    // add member functions to add/remove charNode's from the list etc
    // and implement one of "the rule of 3" or "the rule of 5"

private:
    charNode* head = nullptr;
};

CodePudding user response:

You can implement getCharNode() function like in following code. I used this function for an example of creating singly linked list of chars. Also created extra function print_list() which outputs linked list to console.

Notice that I did only allocation of nodes (new operator), and didn't do deallocation (delete), I left this task for you to do, if you care about memory leaks.

Try it online!

#include <iostream>

// Structures
struct charNode {
    charNode(char value, charNode * _next = nullptr)
        : Node(value), next(_next) {}
    char Node;
    charNode *next;
};

// Functions
charNode* getCharNode(char c, charNode * next = nullptr) {
    return new charNode(c, next);
}

void print_list(charNode const * node) {
    if (!node)
        return;
    std::cout << node->Node << " ";
    print_list(node->next);
}

int main() {
    charNode * list = getCharNode('a',
        getCharNode('b', getCharNode('c')));
    print_list(list);
}

Output:

a b c
  • Related