[英]Unable to create a linked list with given number of elements
I have been given a sequence of integers & I need to create a linked list from them.我得到了一个整数序列,我需要从它们创建一个链表。 I have tried the following code but it is erroring out with 'Runtime error'.我已经尝试了以下代码,但它因“运行时错误”而出错。 I couldn't figure out what's the issue with this code snippet.我无法弄清楚这个代码片段有什么问题。
#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;
}
Hope be useful希望有用
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.