Pass by Reference for Linked List

Hello,
I cant get my insert function to insert to the head of the list I dont think I'm passing the pointers correctly.

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
69
70
71
72
73
#include <iostream>
using namespace std ;

struct list1 {

int data ;
list1 * next = NULL;

};

struct list2 {

int data ;
list2 * next = NULL ;

};

bool isList1Empty ( list1 * head ) ;
bool isList2Empty ( list2 * head ) ;
void printList1 ( list1 * head ) ;
void printList2 ( list2 * head ) ;
void insertList1 ( list1 ** head , int toInsert ) ;
void insertList2 ( list2 * head , int toInsert ) ;

int main () {

    list1 * headptr1 = NULL ;
    list2 * headptr2 = NULL ;
    insertList1 ( & headptr1 , 5 ) ;
}


bool isList1Empty ( list1 * head ) {

    if ( head == NULL )
        return true ;

}

bool isList2Empty ( list2 * head ) {

    if ( head == NULL )
        return true ;

}

void printList1 ( list1 * head ) {

if (isList1Empty(head) == true)
    cout << "List 1 Is Empty\n" ;

}

void printList2 ( list2 * head ) {

    if (isList2Empty(head) == true)
        cout << "List 2 Is Empty\n" ;

}

void insertList1 ( list1 * head , int toInsert ) {

    if (isList1Empty(head) == true) {

        list1 * newNode = new list1 ;
        newNode->data = toInsert ;
        head = newNode ;
        cout << head->data << endl;
    }

}

The method you are calling on line 29 is:

void insertList1 ( list1 ** head , int toInsert ) ;

Which you have not yet defined/implemented
So would I just need a regular pointer or a pointer to a pointer?
I don't understand your question. You are calling this method:

void insertList1 ( list1 ** head , int toInsert ) ;

So you need to actually tell the program what to do when that method is called by putting some code inside the method body:

1
2
3
4
void insertList1 ( list1 ** head , int toInsert )
{
    // code goes here
}
Here is what I implemented it with:

1
2
3
4
5
6
7
8
9
10
11
void insertList1 ( list1 ** head , int toInsert ) {

    if (isList1Empty(head) == true) {

        list1 * newNode = new list1 ;
        newNode->data = toInsert ;
        (*head) = newNode ;
        cout << head->data << endl;
    }

}
Topic archived. No new replies allowed.