#include
<
stdio.h
>
#include
<
malloc.h
>

typedef
struct
node
//
定义双链表
{
int data;
struct node *prior;
struct node *next;
}
snode;

snode
*
creat()
//
创建双链表
{
snode *head, *p, *q;
int x;
head = (snode *)malloc(sizeof(snode));
q = head;
printf("请输入创建双链表的值,以-1结束. ");
printf("x = ");
scanf("%d", &x);
while (x != -1)
{
p = (snode *)malloc(sizeof(snode));
p->data = x;
q->next = p;
p->prior = q;
q = p;
printf("x = ");
scanf("%d", &x);
}
q->next = NULL;
return head;
}

void
display(snode
*
head)//便利打印双链表
{
snode *p = head->next;
while (p != NULL)
{
printf("%4d", p->data);
p = p->next;
}
printf(" ");
}

int
length(snode
*
head)
//
测链表的结点数
{
snode *p = head->next;
int i = 0;
while (p != NULL)
{
p = p->next;
i++;
}
return i;
}

void
opposite(snode
*
head)
{
snode *p = head->next;
while (p->next != NULL)
{ p = p->next;}
while (p != head)
{
printf("%4d", p->data);
p = p->prior;
}
printf(" ");
}

int
insnode(snode
*
head,
int
x,
int
i)
//
把x插入到链表的第i的位置,即在第i个元素p之前插入,与单链表在p之后插入相区别
{
snode *p = head, *s;
if(i < 1 || i > length(head) + 1||!p)
return 0;
else
{
s = (snode *)malloc(sizeof(snode)); //分配内存
for (int j = 0; j < i ; j++)
{
p = p->next;
}
s->data = x;
s->prior = p->prior;//插入 四步完成
s->next = p;
p->prior->next = s;
p->prior = s;
}
return 1;
}

int
delnode(snode
*
head,
int
i)
//
删除链表中第i个结点
{
snode *p = head;
if(i < 1 || i > length(head)||!p)
return 0;
else
{
for (int j = 0; j < i; j++)
{
p = p->next;
}
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
}
return 1;
}
int
main(
void
)
{
snode *headl = creat(); //创建双链表
printf("最初的链表如下: ");
display(headl);
printf("为了证明是双链表反向输出: ");
opposite(headl);
int num, location;
printf("请分别输入您要插入到链表中的数以及想插入的位置:");
scanf("%d %d", &num, &location);
if (insnode(headl, num, location))
{
printf("插入新值以后的链表如下: ");
display(headl);
printf("为了证明插入新值以后仍然是双链表,反向输出如下: ");
opposite(headl);
}
else
printf("输入有误 ");
printf("请输入您想删除的结点位置:");
scanf("%d", &location);
if (delnode(headl, location))
{
printf("删除第%d个结点后的链表如下: ", location);
display(headl);
printf("为了证明删除一个结点以后仍然是双链表,反向输出如下: ");
opposite(headl);
}
else
printf("输入有误! ");
}
转自http://blog.youkuaiyun.com/tanlingyun/article/details/1583834