How do I create three nodes with only 1 variable?

node 1 should be 1
node 2 should be 2
node 3 should be 3
head points to node 1
1
2
3
4
5
6
7
struct Node{
    int data;
    Node *next;
};
Node *h;
h = new Node;
h->data = 1;

I'm not allowed to declare another variable, yet I need three nodes for the linked list. I'm not sure how to do this.
Last edited on
Take a look at this

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
#include <iostream>
using namespace std;

struct Node {
	int data;
	Node* next;
};

// only for the 1st Node
void initNode(struct Node *head,int n){
    head->data = n;
    head->next =NULL;
}
void addNode(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;

    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }
        cur = cur->next;
    }
}

void display(struct Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
    cout << endl;
}

int main() {

    struct Node *newHead;
    struct Node *head = new Node;

    initNode(head,10);
    addNode(head,20);

    display(head);



    return 0;

}
10 20 


Process finished with exit code 0


From
http://www.bogotobogo.com/cplusplus/linkedlist.php#linkedlistexample1

Topic archived. No new replies allowed.