-1

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;
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Biffen Mar 31 '21 at 11:03
  • 1
    ([Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)) – Biffen Mar 31 '21 at 11:03
  • Take a look at your for loop. It creates an instance k and its pointer is added to t->next. After each iteration k is destroyed but t has still a pointer to that destroyed instance. – MatzZze Mar 31 '21 at 11:12
  • You are using objects allocated on the stack `list1 k = list1(temp);` and you take their address. At the end of each loop iteration, that object is gone, therefore the address of `k` will point to rubbish. You need to allocate the list nodes on the heap. And you need to manage their lifetime. – Marius Bancila Mar 31 '21 at 11:29

1 Answers1

-1

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