构造链表的结构体(数据、指针)
struct node{
int data;
node* next;
};
使用new运算符为节点分配内存
node* p = new node;
编写创建列表函数,参数为链表的长度(从用户cin输入读入),返回值为创建的列表的头指针
node* create(int len){
node *p, *pre, *head;
head = new node;
head->next = nullptr;
pre = head;
for(int i = 0; i < len; ++i) {
int num;
cin >> num;
p = new node;
p->data = num;
p->next = nullptr;
pre->next = p;
pre = p;
}
return head;
}
调用create链表main函数
int main(){
int len;
cin >> len;
node* head = create(len);
node* L = head->next;
while(L != nullptr){
cout << L->data << " ";
L = L->next;
}
return 0;
}
输出结果
|