我刚刚开始学习使用C ++的链接列表。我正在尝试使用矢量创建一个链表。为什么此代码有问题?

不是
#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);
 }

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

输出未显示任何内容。没有错误,没有输出。

kb

您正在将null指针(head传递到中createList,但是您在函数中使用以下这一行立即取消引用它:

head->data = v[0];

在尝试使用它之前,head必须指向一些东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档