双链表--尾插法构造(c语言)
#include <stdio.h>
#include <stdlib.h>
// 参数说明:data 存储数据
// prior 指向直接前驱的指针
// next 指向后继节点的指针
typedef struct DNode
{
int data;
DNode *prior;
DNode *next ;
}DNode;
void create_tail_DLinklist(DNode *&head)//采用尾插法构建双链表
{
head = (DNode*)malloc(sizeof(DNode) );
head->data = 0 ;
head->prior= NULL ;
head->next = NULL ;//创建头结点
DNode * p = head; // 指向头结点
int n;
printf("请输入创建双链表的长度:");
scanf("%d",&n);
while(n--)
{
DNode* q = (DNode*)malloc(sizeof(DNode));
scanf("%d",&q->data);
q->next = NULL ; //不能写成q->next = head->next;否则,死循环吧?
q->prior = p;
p->next = q ;
p = q ;
}
}
void Print_DLinklist(DNode *&head)
{
DNode * p = head ;
DNode * q = NULL ;
p = p->next ;
while (p != NULL)
{
printf("%d ",p->data); // 从前往后输出
q = p ;
p = p->next ;
}
}
int main()
{
DNode * head ;
create_tail_DLinklist(head);
Print_DLinklist(head);
return 0;
}
运行结果: