How do I pass variable to function?
May 20, 2013 at 6:08am UTC  
Hey guys, so I am trying to build a simple Linked List (Just practice NOT a homework assignment). I managed to make it without the use of functions but then my main was pretty long. So now I am trying to condense it into by using some function calls. My question is, how do I get my display function to work after I have inserted my values in my list. 
1 #include <iostream> 
using  namespace  std;
struct  node{
	int  data;
	node *next;
};
void  insert(int , node*);
void  display(node*); 
int  main(){
	int  x = 0;
	node *myNode = 0;
	while (x != -1){
		cout << "please enter a number: " ;
		cin >> x;
		if (x == -1){
			cout << "good bye!"  << endl;
		}
		else {
			insert(x, myNode);
		}
	}
	display(myNode);
	system("pause" );
	return  0;
}
void  insert(int  x, node *temp){
	node *head = NULL;
	temp = new  node;
	temp->data = x;
	temp->next = head;
	temp = head;
}
void  display(node *myNode){ //I can't seem to get my function to read in temp^^ 
	while (myNode != NULL){
		cout << myNode->data << " " ;
		myNode->next = myNode;
	}
}
 
May 20, 2013 at 8:44am UTC  
Your function insert is invalid. 
 
May 20, 2013 at 11:25am UTC  
myNode is your list head.  You need to pass it to insert as a pointer to a pointer, or as a pointer by reference. 
 
May 20, 2013 at 11:56am UTC  
Try the following code.
1#include <iostream> 
#include <cstdlib> 
using  namespace  std;
struct  node
{
	int  data;
	node *next;
};
void  insert( node **, int  );
void  display( node ** ); 
void  clear( node ** );
int  main()
{
	int  x;
	node *head = 0;
	while  ( true  )
	{
		cout << "please enter a number: " ;
		cin >> x;
		if  ( !cin || x == -1 )
		{
			cout << "good bye!"  << endl;
			break ;
		}
		insert( &head, x );
	}
	display( &head );
	clear( &head );
	system( "pause"  );
	return  0;
}
void  insert( node **head, int  x )
{
	node *temp = new  node;
	temp->data = x;
	temp->next = *head;
	*head = temp;
}
void  display( node **head )
{ 
	for  ( node *n = *head; n != NULL; n = n->next )
	{
		cout << n->data << " " ;
	}
} 
void  clear( node **head )
{ 
	while  ( node *n = *head  )
	{
		*head = ( *head )->next;
		delete  n;
	}
} 
Last edited on May 20, 2013 at 9:46pm UTC  
 
Topic archived. No new replies allowed.