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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#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.
You have head and temp reversed. head needs to be the argument and temp should be the local variable.
The assignment in line 41 is reversed.
May 20, 2013 at 11:56am UTC
Try the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
#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.