c++ - Linked list, add node to end -
i'm working on project , given function complete
void addtoend(node*& head, string newval) effect: adds new node tail end of list precondition: head pointer first node in list (list may empty) postcondition: list contains 1 more node
my question string newval for?
the value_type of class of type double i'm confused string newval for. can't set newval in node because of 2 different types.
this have far. i'm not sure if im going in right direction.
node *temp = new node; temp = head; while(temp->link() != null){ temp = temp->link(); } head->set_link(temp);
i'm not sure use string in block of code.
link()
returns member variable node* link_field
set_link()
sets new link link_field
well, we're guessing somehow expect turn string double function std::stod
.
as list manipulation code, there's few problems:
node *temp = new node; temp = head;
this creates new node, puts pointer in temp
, overwrites temp
head
, losing (leaking) new node. don't that.
while(temp->link() != null){ temp = temp->link(); }
this close, might not work. problem need keep track of real node pointer, not copy.
normally, in linked list api using pointers instead of references, "add node" function looks like:
void addtoend(node** head, string newval) { while(*head) head = &((*head)->next); *head = new node; (*head)->value = newval; (*head)->next = 0; }
note if list empty, passed-in head pointer altered point new node. if list not empty, last next
pointer altered instead.
the api you're given (i.e. link
, set_link
methods) doesn't allow this, because head pointer not node
, functions require node
. you've got little differently, namely have handle empty list case separately.
void addtoend(node*& head, string newval) { // create node. node* newnode = new node; newnode->value = std::stod(newval); newnode->set_link(0); if(!head) // empty list? { head = newnode; return; } // find last node. node* item = head; while(item->link()) item = item->link(); item->set_link(newnode); }
Comments
Post a Comment