【问题标题】:I have just started learning about Linked list using C++. I am trying to create a linked list using a vector. Why is the problem with this code?我刚刚开始学习使用 C++ 的链表。我正在尝试使用向量创建一个链表。为什么这段代码有问题?
【发布时间】:2021-02-07 05:46:15
【问题描述】:
#include<bits/stdc++.h>
using namespace std;
class node{
public:
    int data;
    node* next;
    
// Constructor
node(int d){
    data = d;
    next = NULL;
}
};

 // Linked List from Vector
void createList(node*& head , vector<int> v){
cout<<v[0];
head->data = v[0];
head->next = NULL;
node* last = head;
for(int i = 1 ; i < v.size() ; i++){
    cout<<"X"<<endl;
    node* temp = new node(v[i]);
    last->next = temp;
    last = temp;
}
cout<<head->data;
  }

// Print Linked list
  void printList(node* head){
  while(head != NULL){
    cout<<head->data;
    head = head->next;
 }
}
int main(){
 vector<int> v = {1 , 2 , 3 , 4 , 5};
 node* head = NULL;
 createList(head , v);
 cout<<head->data;
 printList(head);
 }

上面这段代码是我使用的。首先,我创建了一个向量。然后我使用 tht 向量创建了一个链表 然后我正在尝试打印链接列表。但是输出什么也没显示。

输出什么也不显示。没有错误,没有输出。

【问题讨论】:

标签: c++ linked-list singly-linked-list


【解决方案1】:

您正在将一个空指针 (head) 传递给 createList,但您正在使用此行立即在函数中取消引用它:

head->data = v[0];

在您尝试使用它之前,head 必须指向某个东西。

【讨论】:

  • 是的,我应该先为头部分配内存...thanx
猜你喜欢
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2021-12-24
  • 2018-06-16
  • 2011-04-07
相关资源
最近更新 更多