c++中创建链表可以直接通过new对象的方式创建节点,然后将节点之间的关系通过next指针来关联起来,另外,也可以通过malloc来分配内存,创建节点。这里介绍如何通过malloc来创建链表。
malloc分配内存的方式为malloc(sizeof(typename)),最后 还需要通过类型转换,将它转为(typename *),如下所示:
node *p=NULL;
p = (node *)malloc(sizeof(node));
下面给出一个代码示例,我们通过代码来创建一个链表,使用一个循环依次为链表的节点赋值:
#include <iostream>
using namespace std;
#define SIZE sizeof(node)
struct node{
int data;
node *next;
};
node *create(){
node *head = NULL;
node *p = NULL;
node *cur;
for(int i=1;i<=5;i++){
p = (node *)malloc(SIZE);
p->data = i;
p->next = NULL;
if(head==NULL){
head = p;
cur = head;
}else{
cur->next = p;
cur = cur->next;
}
}
return head;
}
void display(node *head){
cout<<"list no