# 【数据结构】双向链表插入元素

#include <stdio.h>
#include <stdlib.h>

{
int data;
int length;

int Insert(pDoubleLink L, int data, int pos);

int main(void)
{
int n, data, pos, flag;
L->prior = L->next = NULL;
L->length = 0;

printf("输入需要创建的链表元素个数:");
scanf("%d", &n);
Create(L, n);

printf("输入需要插入的元素值:");
scanf("%d", &data);
printf("输入需要插入的元素的位置:");
scanf("%d", &pos);

flag = Insert(L, data, pos);
if (flag < 0)
{
printf("output:\nThe Position is Wrong!\n");
}

if (flag >= 0)
{
Doubleout(L);
}

Destroy(L);
free(L);
return 0;
}

/*头插法创建双向链表*/
{
int i, data;
printf("输入创建链表各元素的值:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &data);

p->data = data;
p->next = L->next;
p->prior = L;

if (L->next != NULL)
{
L->next->prior = p;
L->next = p;
}
else
{
L->next = p;
}
}
}

{
printf("output:\n");
while (p->next != NULL)
{
printf("%d ", p->next->data);
p = p->next;
}
printf("\n");
while (p != L)
{
printf("%d ", p->data);
p = p->prior;
}
printf("\n");
}

{

p = q = L->next;
while (p != NULL)
{
q = p->next;
free(p);
p = q;
}
}

/******start******/
int Insert(pDoubleLink L, int data, int pos)
{
int i;
p = L;
q->data = data;
q->next = NULL;
if(pos <= 0)
{
return -1;
}
for(i = 1; i <= pos - 1; i++)
{
p = p->next;
if(p->next == NULL && i < pos - 1)
{
return -1;
}
}
if(p->next != NULL)
{
p->next->prior = q;
}
q->next = p->next;
p->next = q;
q->prior = p;
return 1;
}
/******end******/


12-18 3108

01-07 2096
08-18 2216
07-19 883
09-27 209
04-23 1767
03-09 8504
12-10 480
05-20 2295
09-12 979
03-21 155
05-04 433
04-26 4133
05-06 2万+