直接上例子
int main() { int a1[]={3,4,2}; int a2[]={4,6,5}; Listnode *head=NULL,*temp; head=(Listnode*)malloc(sizeof(Listnode));//头节点 head->next=NULL; /*1.new node in head->next,head on the botom for (int i=0;i<3;i++) { temp=(Listnode*)malloc(sizeof(Listnode)); temp->val=a1[i]; temp->next=head->next;//先把上一次插入的链表打断,接入新插入节点的后面 head->next=temp;//然后把链条接入头节点的下面。于是:每一个新节点都插入到头节点之后,于是倒序了
}*/
/*2. */
Listnode *r;
r=head; //地址
for (int i=0;i<3;i++)
{
temp=(Listnode*)malloc(sizeof(Listnode));
temp->val=a1[i];
r->next=temp; //每一个新节点都插入到了原来链条的最后,并且链条向后走了一步
r=temp; //更新最后一个节点
}
r->next=NULL; //把最后节点指向NULL
temp=head->next;//将链表移到首结点开始打印
while (temp)
{
cout<<"->"<<temp->val<<endl;
temp=temp->next;
}
return 0;
}