c++链表问题
C++ Linked list issue
我一直在做一个小的个人项目,并且遇到了一个障碍。该项目的目的是添加到我的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);
}
相关文章:
- 链表指针问题
- 我对数据结构、双向链表有一些问题
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- Sinlge 链表,C++,删除所有和搜索功能的问题
- C++ 从链表中删除项目时出现问题
- 如何修复我的链表读数不一致的问题?
- C++中链表实现的问题
- 双向链表问题 - 包含项目但不显示
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 在链表中的某个点插入时出现问题,C++中的继承函数
- cpp 中的以下链表程序有什么问题?
- 单个链表,节点插入最低到最高节点值的问题
- 我在让我的代码输出整个链表时遇到问题.它只是输出我修改过的一些文本文件,而不是整个东西
- 双向链表问题(特别是复制构造函数和删除函数)
- 我在双链表上的此打印功能时遇到问题
- 我在显示链表时遇到问题
- 尝试在链表程序的末尾进行更简单的插入.小问题需要帮助
- 节点和链表问题
- c++理解问题-链表和堆栈
- C++语法问题(链表)