#include#includeusing namespace std;typedef struct Node2{ int num; Node2 *next; Node2 *pre;}Node2;//定义节点void init(Node2 *head,int len){//初始化链表长度 Node2 *head2=head; for(int i=0;i<len;i++){//尾插法 Node2 *node=(Node2 *)malloc(sizeof(Node2));//创建一个节点,因为是malloc函数分配,分配的空间并不会因为函数运行结束而结束 node->num=i;//给节点赋值 head2->next=node;//将新节点的地址会给上一个节点的next,形成链表 node->pre=head2;//指向前一个节点 head2=node;//移动到新节点,也就是最后一个节点,然后继续循环 } head2->next=NULL;//最后一个节点,next的值要为NULL}void print(Node2 *head){ //从前面打印 Node2 *head1=head->next,*back;//头结点没有数值,所以先移动到下一个节点 while(head1!=NULL){ cout<<head1->num<<" "; back=head1; head1=head1->next;//移动到下一个节点 } cout<<endl; //从后面打印 Node2 *head2=back; while(head2!=NULL){ if(head2->pre!=NULL)cout<<head2->num<<" ";//不要把头结点的值读出来 head2=head2->pre;//移动到前一个节点 } cout<<endl;}int main(int argc, char const *argv[]){ Node2 *head=(Node2 *)malloc(sizeof(Node2)); head->next=NULL; head->pre=NULL; //双向链表应该没有必要纠结用头插法或者尾插法 /* 输入:传入头节点,初始化的长度 返回:空 */ init(head,5); /* 输入:传入头节点,初始化的长度 打印结果 返回:空 */ print(head); return 0;}