英文:
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;
这句话的英文翻译是:
- 头指针指向节点
N
。 - 尾指针指向节点
N
。
所以当我们执行以下操作:
L.head->n = 4;
L.tail->n = 5;
这表示:
- 将
L.head->n
(即N.n
)更改为 4。 - 将
L.tail->n
(即N.n
)更改为 5。
因此,头指针和尾指针都指向相同的东西。你将该东西更改为 5,因此它们都返回 5。
英文:
Lets read this line closely:
L.head = &N;
L.tail = &N;
This in english says:
- The head pointer, points at the node
N
. - The tail pointer, points at the node
N
.
So when we do this:
L.head->n = 4;
L.tail->n = 5;
This says:
- Change
L.head->n
which isN.n
to 4. - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论