单链表添加错误
Single Linked List addition fault
单链表添加新列表项的函数
void linked_list::push(int n) {
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if (head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tmp;
}
}
为了显示,我使用了下面的函数代码
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" <<endl;
}
else {
node *tmp = head;
while (tmp->next != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
}
传递一些值后,即 1 2 3 4 我的预期输出是所有给定的值,但它给出以下输出,即 1 2 3
为了将它们全部打印出来,while 中的条件必须是:
while(tmp != NULL)
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" << endl;
}
else {
node *tmp = head;
while (tmp != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
单链表添加新列表项的函数
void linked_list::push(int n) {
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if (head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tmp;
}
}
为了显示,我使用了下面的函数代码
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" <<endl;
}
else {
node *tmp = head;
while (tmp->next != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
}
传递一些值后,即 1 2 3 4 我的预期输出是所有给定的值,但它给出以下输出,即 1 2 3
为了将它们全部打印出来,while 中的条件必须是:
while(tmp != NULL)
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" << endl;
}
else {
node *tmp = head;
while (tmp != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}