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

题目要求:
在这里插入图片描述
源代码:

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

typedef struct _DoubleLink
{
	int data;
	struct _DoubleLink *prior;
	struct _DoubleLink *next;
	int length;
} DoubleLink, *pDoubleLink;

void Create(pDoubleLink L, int n);
void Doubleout(pDoubleLink L);
void Destroy(pDoubleLink L);
int Insert(pDoubleLink L, int data, int pos);

int main(void)
{
	int n, data, pos, flag;
	pDoubleLink L = (pDoubleLink)malloc(sizeof(DoubleLink));		//头结点
	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;
}

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

		p = (pDoubleLink)malloc(sizeof(DoubleLink));
		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;
		}
	}
}

void Doubleout(pDoubleLink L)
{
	pDoubleLink p = L;
	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");
}

void Destroy(pDoubleLink L)
{
	pDoubleLink p, q;
	
	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;
	pDoubleLink p, q;
	p = q = (pDoubleLink)malloc(sizeof(DoubleLink));
	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******/

运行截图:
在这里插入图片描述
在这里插入图片描述

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页