将节点添加到链表的前面 [英] Adding node to the front of a linked list
问题描述
我真的很困惑,这是怎么回事。
我有函数
void addToFront(int data)
{
Node * tmp = new Node();
tmp - > data = data;
tmp - >下一页
head = tmp;
}
所以当我们执行 tmp-> next = head
,我们使 tmp
指针指向头
指向(列表的当前第一个元素)?因为这是它的感觉,但不是只是让它指向 head
?然后,当我们 head = tmp
时,我们正在指向我们创建的新节点,正确?
这是您的列表(假设)
+ + ----- + + ----- + ----- + + ----- + ------ +
| A | + - | + - | |
+ ---- + ----- + + ----- + ----- + + ----- + ------ +
/
头
指向 A
<$> c $ c> + ---- + ---- +
| B | |
+ ---- + ---- +
/
code> tmp 现在指向 B
。在 tmp-> data
中插入数据,然后使 tmp - > next = head;
。现在我们有:
+ ---- + ---- + + ---- + - + + ----- + ----- + + ----- + ------ +
| B | next | ----> | A | + - | + - | |
+ ---- + ---- + + ---- + ----- + + ----- + ----- + + ----- + --- --- +
/
然后你使 / code>指向
B
而不是 A
。
+ ---- + ---- + + ---- + ----- + + ----- + ----- + + ----- + ------ +
| B | next | ----> | A | + - | + - | |
+ ---- + ---- + + ---- + ----- + + ----- + ----- + + ----- + --- --- +
/ \
head
& tmp
现在指向 B
。
I'm really confused as to what exactly is going on here..
I have the function
void addToFront(int data)
{
Node* tmp = new Node();
tmp -> data = data;
tmp -> next = head;
head = tmp;
}
So when we do the line tmp-> next = head
, we are making the tmp
pointer point to what head
is pointing to (the current first element of the list)? Because that's what it feels like, but wouldn't that just make it point to head
? And then when we do head = tmp
, we are making head point to the new node that we created, correct?
This is how your list was (suppose)
+----+-----+ +-----+-----+ +-----+------+
| A | +-->| | +-->| | |
+----+-----+ +-----+-----+ +-----+------+
/
Head
is pointing to location A
.
You make a new node
+----+----+
| B | |
+----+----+
/
tmp
now points to B
. You insert data in tmp->data
, and then make tmp -> next = head;
. So now we have:
+----+----+ +----+-----+ +-----+-----+ +-----+------+
| B |next|---->| A | +-->| | +-->| | |
+----+----+ +----+-----+ +-----+-----+ +-----+------+
/
And then you makehead
to point to B
instead of A
.
+----+----+ +----+-----+ +-----+-----+ +-----+------+
| B |next|---->| A | +-->| | +-->| | |
+----+----+ +----+-----+ +-----+-----+ +-----+------+
/ \
head
& tmp
point to B
now.
这篇关于将节点添加到链表的前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!