我刚刚开始使用 C++ 学习链表。我正在尝试使用向量创建链表。为什么这段代码有问题?
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?
#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 vector 创建了一个链表
然后我试图打印链表。但是输出什么也没有显示。
输出没有显示任何内容。没有错误,没有输出。
您正在将一个空指针 (head
) 传递给 createList
,但您在函数中使用以下行立即取消引用它:
head->data = v[0];
在您尝试使用它之前,head
必须指向某物。
#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 vector 创建了一个链表 然后我试图打印链表。但是输出什么也没有显示。
输出没有显示任何内容。没有错误,没有输出。
您正在将一个空指针 (head
) 传递给 createList
,但您在函数中使用以下行立即取消引用它:
head->data = v[0];
在您尝试使用它之前,head
必须指向某物。