Singly linked list add at end

Pages: 12
closed account (4ET0pfjN)
Just to make sure, we pass by pointers to pointers rather than pass by a regular pointer b/c we'd just pass the pointers by value but we want to modify the actual head and tail pointers in main function, right so we need to go to the address of the head and tail pointers, right?

void add_at_end(string node_data, sll_node *front, sll_node *end);
This is wrong b/c we are copying the address into this function so we need to go directly to that address

which explains why it must be:
void add_at_end(string node_data, sll_node **front, sll_node **end);

OR we can references but benefits of using pointeres to pointers versus references for add_at_end function?
Last edited on
Just to make sure, we pass by pointers to pointers rather than pass by a regular pointer b/c we'd just pass the pointers by value but we want to modify the actual head and tail pointers in main function, right so we need to go to the address of the head and tail pointers, right?
Right.

References to pointers would do as well as pointers to pointers. Either one will do.
closed account (4ET0pfjN)
two more things(hopefully), why doesn't this output the linked list content? And problems with my search function...

1
2
3
4
5
6
7
8
9
10
void showList(sll_node **front)
{
   sll_node **front_copy = front;
	
   while ( *front_copy != NULL )
   {
	 cout << **front_copy << " ";
	 *front_copy = (*front_copy)->next;
   }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool search(string findMe, sll_node **front)
{
	bool isFound = false;
	
	sll_node **first = front;
	
	while ( *first != NULL )
	{
		if ( (**first)->data == findMe)
		{
			isFound = true;
			break;
		}
		*first = *first->next;
	}
	
	return isFound;
}


1
2
3
4
5
6
7
8
9
10
11
int main()
{
   sll_node *front = new sll_node;
   sll_node *end = new sll_node;
   front = NULL; end = NULL;
	
   add_at_end("A", &front, &end);
   showList(&front);

   return 0;
}
Last edited on
closed account (4ET0pfjN)
I figured out search function mistake, in the while loop it should be:
if ( (*first)->data == findMe)

but what am I doing wrong for the showList function?
You should really stop going nuts with the **s.

Ask yourself, "Do I need a pointer to a pointer here? Do I need to modify the original pointer value?"

1
2
3
4
5
6
7
8
9
10
void showList(sll_node *front)
{
   sll_node * current = front ;
	
   while ( current )
   {
	 cout << current->data << " ";
         current = current->next ;
   }
}


Apply any lessons you learn here to search.

closed account (4ET0pfjN)
thanks for that,

"Do I need a pointer to a pointer here? Do I need to modify the original pointer value?"
Topic archived. No new replies allowed.
Pages: 12