我正在尝试按输入顺序打印链接列表,例如,如果我输入数据集'a','b',c','d',我想以相同的顺序打印出来,但是由于某种原因,我的代码始终从末尾开始并向后遍历?而且我们不允许使用类,而只能使用结构
#include <iostream>
using namespace std;
struct node {
string data;
node* next;
};
node* addFront(node* s);
void remove(node* head, node* n);
void print(node* head);
int main() {
node* head = NULL;
node* temp = head;
cout << "Enter 5 data data strings\n";
for (int i = 0; i < 5; i++) {
head = addFront(head);
}
print(head);
}
node *addFront(node*s ) {
node* person = new node;
cin >> person->data;
person->next =s;
s = person;
return s;
}
void remove(node* head, node* n){
if (head == n) {
if (head->next == nullptr) {
cout << "There is only one node and that is he head node\n";
}
head->data = head->next->data;
n = head->next;
head->next = head->next->next;
}
}
void print(node * head)
{
node* temp = head;
while (temp != NULL) // don't access ->next
{
cout << temp->data << endl;
temp = temp->next;
}
}
我放入数据集a,b,c,d,e,并打印出e,d,c,b,a
答案 0 :(得分:0)
由于temp-> next未初始化为NULL,因此似乎在打印功能中可能发生内存访问冲突。
node* person = new node;
cin >> person->data;
person->next = NULL; // preferred
下面的是FIFO的示例之一。只需返回头指针,每次循环就找到最后一个元素。
node* pushBack(node* h) {
node* person = new node;
cin >> person->data;
person->next = NULL;
if (h == NULL) {
h = person;
}
else {
node* last = h;
while (last->next != NULL) {
last = last->next;
}
last->next = person;
}
return h;
}
或者,使用函数参数同时使用头指针和最后一个元素指针会更好,因为这会减少while循环。