本帖最后由 漠水 于 2014-11-5 09:46 编辑 #include<stdio.h>
#include<malloc.h>
#define NULL 0
typedef struct h
{
int n;
struct h * next;
struct h * qian;
}h;
h *creat() //双向链表创建
{
int a;
h *head,*r,*p;
head=(h *)malloc(sizeof(h)); //头指针初始前驱节点为NULL,后续初始节点为NULL
head->next=NULL;
head->qian=NULL;
head->n=NULL;
r=head; //r指向头指针
printf("请输入数字以-1作为结束标志:\n");
scanf("%d",&a);
while(a!=-1)
{ p=(h *)malloc(sizeof(h)); //建立节点,使r指向它
r->next=p; //r的后续节点为p,p的前驱节点为r,后续节点为NULL,数值等于输入数值
p->n=a;
p->qian=r;
p->next=NULL;
r=p; //r指向下一节点
scanf("%d",&a);
}
return head;
}
void print(h *head) //双向链表显示
{
h *p;
p=head;
if(p->next==NULL)printf("\n空表\n");
else
{
printf("\n");
while(p->next!=NULL)
{
p=p->next;
printf("%d ",p->n);
}
printf("\n");
}
}
void main()
{ h *head;
creat();
print(head);
}
|