无法创建具有给定元素数的链表



我得到了一个整数序列&我需要从它们创建一个链接列表。我已经尝试了以下代码,但它出现了"运行时错误"。我不知道这个代码片段出了什么问题。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class list1 {
public:
int val;
list1 *next;
list1(int x) : val(x), next(NULL) {}
};
int main() {
int n;
cin >> n;
list1 *x = NULL;
list1 *t = NULL;
int temp;
cin >> temp;
list1 A = list1(temp);
t = &A;
for (int i = 1; i < n; i++) {
int temp;
cin >> temp;
list1 k = list1(temp);
t->next = &k;
t = t->next;
}
x = &A;
while (x != NULL) {
cout << x->val << " ";
x = x->next;
}
cout << endl;
return 0;
}

希望成为有用的

#include <iostream>
//#include<bits/stdc++.h>
using namespace std;
class list1 {
public: int val;
list1* next;
list1(int x) : val(x), next(NULL) {}
};

int main() {
int n;
cin >> n;
int temp;
cin >> temp;
list1* firstMember= new list1(temp);
list1* lastMember = firstMember;

while (n > 1)
{
n--;
cin >> temp;
list1 newMember(temp);
lastMember->next =new list1(temp);
lastMember = lastMember->next;
}
list1* ListNavigator = firstMember;
while (ListNavigator != NULL)
{
cout << ListNavigator->val << " ";
ListNavigator = ListNavigator->next;
}

cout << endl;
return 0;
}

相关内容

  • 没有找到相关文章

最新更新