简体   繁体   English

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

[英]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.

相关问题 无法创建由“父级”链接的元素列表 - Can't create a list of elements linked by a “Parent” 无法创建或返回反向链接列表 - Unable to create or return Reversed Linked list 从给定位置开始的简单链接列表中删除元素 - Delete elements from a simple linked list starting at given position 在偶数个元素的情况下打印链表的中间 - Printing middle of a linked list in case of even number of elements 如何计算双向链表中的元素数? - How to count number of elements in a doubly-linked list? 我正在尝试计算链接列表中当前的元素数量 - I am trying to count the number of elements currently in a linked list C++ - 链表 - 无法创建临时节点 - C++ - Linked List - Unable to create a temporary node 如何使用给定数量的元素初始化boost :: python :: list? - How to initialize boost::python::list with a given number of elements? 给定一个链结列表具有奇数个节点的情况,仅遍历列表一次即可找到中间节点的2种方法是什么? - Given a single linked list with an odd number of nodes, what are 2 ways of finding middle node by traversing list only once? 我无法使用以下代码反转给定的链表。 有人可以指出代码中的错误吗? - I am unable to reverse the given linked list with the following code. Can someone point out the error in the code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM