这个代码只打印30这个有什么不对吗?
我不知道这个打印怎么只有30?这段代码有什么问题吗?
#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
class LinkedList {
private:
node *head, *tail;
public:
LinkedList() {
head = NULL;
tail = NULL;
}
// For adding nodes
void addNode(int value) {
node *tmp = new node;
tmp->data = value;
tmp->next = NULL;
if(head == tail) {
head = tmp;
tail = tmp;
tmp = NULL;
} else {
tail->next = tmp;
tail = tail->next;
}
}
// For displaying nodes
void display() {
node *tmp = head;
while(tmp != NULL) {
cout << tmp->data << endl;
tmp = tmp->next;
}
}
};
int main()
{
LinkedList a;
// For adding nodes
a.addNode(10);
a.addNode(20);
a.addNode(30);
// For displaying nodes
a.display();
return 0;
}
qazxsw poi条件总是返回true:
if
在第一次插入时它返回true,因为head和tail是NULL。在第二次插入时,这个条件也返回true,因为head和tail是相同的,依此类推。因此,您不添加新项目,但始终覆盖第一项。
你应该修理它
if(head == tail) {
我认为错误是在行if(head == tail),如果你将它改为if(head == NULL)它应该打印10 20 30.但是,如果你想知道为什么if(head == tail)导致这个问题是因为每个addNode操作的head和tail都是相同的,而且最后head也是30!