首页 > 解决方案 > 无法创建具有给定数量元素的链表

问题描述

我得到了一个整数序列,我需要从它们创建一个链表。我已经尝试了以下代码,但它因“运行时错误”而出错。我无法弄清楚这个代码片段有什么问题。

#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;
}

标签: c++linked-list

解决方案


希望有用

#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;
}

推荐阅读