c++ - 无法创建具有给定数量元素的链表
问题描述
我得到了一个整数序列,我需要从它们创建一个链表。我已经尝试了以下代码,但它因“运行时错误”而出错。我无法弄清楚这个代码片段有什么问题。
#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;
}
推荐阅读
- python - 删除几乎相同的行 numpy 数组
- git - 如何在不使用 git reflog 的情况下恢复丢失的提交?
- api - Jira API 未过滤字段
- python-3.x - Python 3:抛出 NameError 的递归错误(BST 问题)
- spring - 使用 CrudRepository#getOne() 时如何检查是否存在
- java - Apache Common Math、Lombok、Apache Common Lang、Slf4j 是纯 Java 吗?
- java - 即使没有直接初始化,Java 也会创建对象吗?
- php - 将ul li列表转换为字符串路径
- java - 是什么导致 Android Studio 将 FragmentManager 标记为已弃用?
- javascript - 我的网站可以在台式机上运行,但不能在移动设备上运行。涉及很多 JavaScript。任何想法如何诊断这个?