1

I'm writing a C++ programm which has to work with linked list. But I can't figure out how can I access structure which is in another structure.

#include <cstddef>
#include "list.hpp"
using std::size_t;

struct list {
    struct node {
        double val;
        node* prev;
        node* next;
    };

    node* head = nullptr;
    node* tail = nullptr;
    size_t size = 0;
};

Can you explain me how it works? I have a method, but I don't know how I can use this structur in this method.

void push_back(list& l, double elem) {
    node *new_node = new node(elem);
    if (l.head==null) {
        l.head = new_node;

    }
    node *curent = l.head;
    while (curent) {
        if (!curent->next) {
            curent->next = new_node;
        }
        cur = cur->next;
    }
}

Thank you.

8
  • 4
    list::node instead of just node Commented Mar 28, 2016 at 20:43
  • You haven't defined a node constructor, so you can't do new node(elem). Commented Mar 28, 2016 at 20:44
  • @Barmar so you mean it has to be like this list::node *new_node = new list::node(elem);? Commented Mar 28, 2016 at 20:49
  • You still need to define a constructor that tells it how to initialize the new node with the elem argument. Commented Mar 28, 2016 at 20:52
  • @Barmar can you make an example? Commented Mar 28, 2016 at 20:53

1 Answer 1

1

in this code , you have a doubly linked list

i'll try to explain the code of the push_back function .

at the beginning we have void push_back(list& l, double elem) , l is your current LinkedList whish you want to add a new element to it in queue, elem is the value of your new element .

if (l.head==null) {
    l.head = new_node;
}

if your linkedList is empty , we add the new element

exemple1 : empty LinkedList

if the linkedList is not empty

push back

this a simple code

    node *curent = l.head; // the current node is pointed to the head of the LinkedList
    while (curent->next != null) { // while current->next is not equal to null
            curent=curent->next ; // step forward to the next node
        }
        curent->next =new_node ; // add the new node to the queue of the linkedList
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.