add list using pointer

May 26, 2019 at 1:06pm
everything is fine, but when I add new node to list, the head and the tail both take that node and remove the old, why?

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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>

using namespace std;

struct data {
    int data;
};

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

struct Llist {
    struct Node *head;
    struct Node *tail;
};

void create(Llist *q){
    q->head = q->tail = NULL;
}

void add(struct Llist *L, struct Node *node){
    struct Node *ptemp = new Node();
    ptemp = node;
    if(L->head == NULL){
        L->head = ptemp;
        L->tail = ptemp;
        ptemp = NULL;
    }
    else {
        L->tail->next = ptemp;
        L->tail = ptemp;
    }
}

int main(void)
{
    /* request auto detection */
    struct Llist lis;
    create(&lis);
    struct data da;
    struct Node node;
    da.data = 5;
    node.da = da;
    node.next = NULL;
    add(&lis, &node);
    cout << lis.head->da.data << "__" << lis.tail->da.data << endl;
    da.data = 6;
    node.da = da;
    add(&lis, &node);
    cout << lis.head->da.data << "__" << lis.tail->da.data << endl;
    da.data = 7;
    node.da = da;
    add(&lis, &node);
    cout << lis.head->da.data << "__" << lis.tail->da.data << endl;
    da.data = 8;
    node.da = da;
    add(&lis, &node);
    cout << lis.head->da.data << "__" << lis.tail->da.data << endl;
    return 0;

}
May 26, 2019 at 1:45pm
pnthoai123 wrote:
everything is fine

That's what the watchman on the "Titanic" said.

Why do you keep creating new Nodes (line 27) and then changing the only thing that can possibly record their memory location (line 28). A pointer holds a memory location ... not a set of values.
Topic archived. No new replies allowed.