我一直在做一个小的个人项目,并且遇到了一个障碍。该项目的目的是添加到我的Github,但我一直盯着我的代码关闭和上个星期,找不到它出错的地方。这个项目是对我自身能力的一次考验,也是对我对c++中链表的理解程度的一次考验。在我继续之前,这是我的代码
#include <iostream>
using namespace std;
struct payload {
int ID;
int x;
int y;
string name;
};
struct node {
node* prev;
node* next;
bool isRoot;
payload data;
};
node* fillStruct(node* tmp);
void print(node* tmp);
int main(void) {
node* temp;
node* list;
node* iterator;
bool done = false;
int count = 0;
char answer;
do {
temp = new node();
temp = fillStruct(temp);
if (count == 0) {
list = new node();
list = temp;
list->prev = NULL;
list->next = NULL;
list->isRoot = true;
} else {
list->next = temp;
temp->prev = list;
list = new node();
list = temp;
}
count++;
cout << "Will more elements be added to the list?n [Y or N]n";
cin >> answer;
switch (answer) {
case 'y':
case 'Y':
break;
case 'n':
case 'N':
list->next = NULL;
done = true;
break;
default:
break;
}
} while (!done);
while (list->prev != NULL) {
list = list->prev;
}
int identifier = 100;
while (1) {
list->data.ID = identifier;
identifier++;
if (list->next == NULL)
break;
list = list->next;
}
while (list->prev != NULL) {
list = list->prev;
}
while (1) {
print(list);
if (list->next == NULL)
break;
list = list->next;
}
return 0;
}
node* fillStruct(node* tmp) {
if (!tmp) {
cerr << "Unauthorized access. Terminating program";
return tmp;
}
cout << "Please enter the X value.n";
cin >> tmp->data.x;
cout << "Please enter the Y value.n";
cin >> tmp->data.y;
cout << "Please enter the data namen";
cin >> tmp->data.name;
return tmp;
}
void print(node* tmp) {
cout << "Identifier: " << tmp->data.ID << endl;
cout << " X: " << tmp->data.x << endl;
cout << " Y: " << tmp->data.y << endl;
cout << " Name: " << tmp->data.name << endl;
}
代码编译和执行良好。我遇到的问题是在代码的打印阶段。它切断了最后一个元素,我不知道为什么。据我所知,第二个while(1)
应该在打印最后一个元素后终止。如果有人能提供指导,我将不胜感激。先谢谢你,和往常一样,如果有什么需要我澄清的,我会的。
按照您的代码,最好将list
保留在列表头部,并使用指针遍历列表。
node* list = NULL;
node* ptr = NULL; // tail
do {
temp = new node();
temp = fillStruct(temp);
temp->prev = ptr;
temp->next = NULL;
if (ptr) {
ptr->next = temp;
}
ptr = temp;
if (!list) {
list = ptr;
}
count++;
cout << "Will more elements be added to the list?n [Y or N]n";
cin >> answer;
switch (answer) {
case 'y':
case 'Y':
break;
case 'n':
case 'N':
done = true;
break;
default:
break;
}
} while (!done);
int identifier = 100;
for (ptr = list; ptr; ptr = ptr->next) {
ptr->data.ID = identifier;
identifier++;
}
for (ptr = list; ptr; ptr = ptr->next) {
print(list);
}