user12810172
user12810172

Reputation:

C++: Append node to Linked List

This what I need to do: append_data adds a node onto the end of the list pointed to by top. the resulting list is one element longer, and the newly appended node has the given data value. consider using the 'append' function to help. void AppendData(int data);

append is the same as append_data, except we're adding a node, rather than a value. void Append(shared_ptr new_node); I was able to AppendData using this code, but in an ideal world I could pass Append thru AppendData and get the same result. I'm struggling with Append right now even though the answer is in the AppendData code

'''

void LinkedList::AppendData(int data){

    shared_ptr<node> temp(new node);
    temp->data = data;
    temp->next = shared_ptr<node>(NULL);
    
    shared_ptr<node> end_node(top_ptr_);
    
    if(end_node == NULL) {
      end_node=temp;
    } else {
      while(end_node->next!=NULL) {
        end_node=end_node->next;
      }
      end_node->next=temp;
    }
    }
    
void LinkedList::Append(shared_ptr<node> new_node){}

'''

Upvotes: 0

Views: 204

Answers (1)

cigien
cigien

Reputation: 60218

in an ideal world I could pass Append thru AppendData and get the same result.

Actually, Append has less information than AppendData, in particular, the data itself. It would make more sense to refactor it in a way that AppendData creates a node, and then calls Append to append that node to the list:

void LinkedList::AppendData(int data){

    // construct node
    shared_ptr<node> temp(new node);
    temp->data = data;
    temp->next = shared_ptr<node>(NULL);

    // append it
    Append(temp);   
}
    
void LinkedList::Append(shared_ptr<node> new_node){

    shared_ptr<node> end_node(top_ptr_);
    
    if(end_node == NULL) {
      end_node = new_node;  // new_node instead of temp
    } else {
      while(end_node->next!=NULL) {
        end_node=end_node->next;
      }
      end_node->next = new_node;  // ditto
    }
}

Also, this line end_node = new_node; is incorrect. If the list is empty, you need to update top_ptr_ like this:

top_ptr_ = new_node;    

Upvotes: 1

Related Questions