void add_node(int n) {
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tail->next;
}
}
在else语句中,为什么我不能直接分配tail = tmp;而不是tail = tail-> next;我有什么想念的吗?预先感谢!
答案 0 :(得分:1)
让我们列出一个简单的清单:
+-------+ +-------+ +-------+ | node1 | --> | node2 | --> | node3 | +-------+ +-------+ +-------+ ^ ^ | | head tail
现在要在列表末尾添加一个新节点,我们首先通过使尾部next
指针指向新节点来将新节点添加到列表中:
+-------+ +-------+ +-------+ +-------+ | node1 | --> | node2 | --> | node3 | --> | node4 | +-------+ +-------+ +-------+ +-------+ ^ ^ | | head tail
这是作业tail->next = tmp
的工作。
然后我们更新tail
以指向新的尾巴:
+-------+ +-------+ +-------+ +-------+ | node1 | --> | node2 | --> | node3 | --> | node4 | +-------+ +-------+ +-------+ +-------+ ^ ^ | | head tail
这就是作业tail = tail->next
的工作。当然,这也可以通过执行tail = tmp
来完成。
两次分配的顺序很重要。
现在,如果您以相反的方式进行操作,则在有条件时首先分配tail = tail->next
+-------+ +-------+ +-------+ | node1 | --> | node2 | --> | node3 | +-------+ +-------+ +-------+ ^ | head
您不再有尾巴了!除非您遍历整个列表以查找其next
指针为空指针的节点,否则您不知道列表的结尾以及在哪里插入新节点。
答案 1 :(得分:0)
您可以这样做,但是不会产生正确的结果。如果您无法通过查看代码找出原因,请使用调试器对其进行跟踪。