-9

I'm just playing around with a linked list trying to see how it all works. Why is my program printing 5 for both the head and the tail instead of 4 and 5 respectively?

struct Node {

    int n;
    Node *next;

};

class LinkedList {

    public:
        Node *head = NULL;
        Node *tail = NULL;

};

int main() {

    Node N;
    LinkedList L;
    
    L.head = &N;
    L.tail = &N;

    L.head->n = 4;
    L.tail->n = 5;

    cout << L.head->n << endl;
    cout << L.tail->n << endl;

}
Evg
  • 25,259
  • 5
  • 41
  • 83
aci1560
  • 1
  • 4
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Evg Feb 27 '23 at 01:42
  • 1
    `L.head` and `L.tail` both point at `N`. So the assignments `L.head->n` and `L.tail->n` both affect `N.n`. Assigning any `int` the value `4` and then immediately reassigning the same `int` to have the value `5`, means it ends up with the value `5`. – Peter Feb 27 '23 at 01:53
  • 4
    you have got one node, it cant hold 2 values – pm100 Feb 27 '23 at 01:58

1 Answers1

2

Lets read this line closely:

    L.head = &N;
    L.tail = &N;

This in english says:

  1. The head pointer, points at the node N.
  2. The tail pointer, points at the node N.

So when we do this:

    L.head->n = 4;
    L.tail->n = 5;

This says:

  1. Change L.head->n which is N.n to 4.
  2. Change L.tail->n which isN.n to 5.

So the head and the tail both point at the same thing. You change that thing to 5, so both return 5.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175