我的程序为什么没有打印我想要打印的值?

huangapple go评论62阅读模式
英文:

Why is my program not printing the values that I want it to print?

问题

我正在玩一个链表,试图看看它是如何工作的。为什么我的程序打印出头部和尾部都是5,而不是分别是4和5呢?

英文:

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;

}

答案1

得分: 2

让我们仔细阅读这行:

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

这句话的英文翻译是:

  1. 头指针指向节点 N
  2. 尾指针指向节点 N

所以当我们执行以下操作:

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

这表示:

  1. L.head->n(即 N.n)更改为 4。
  2. L.tail->n(即 N.n)更改为 5。

因此,头指针和尾指针都指向相同的东西。你将该东西更改为 5,因此它们都返回 5。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月27日 09:40:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定