循环双链表尾插法创建删除前驱后继遍历

#include 
#include 
#include 
typedef struct List
{
	int data;
	struct List* pier;
	struct List* pnext;
}NODE;
typedef NODE* plist;
typedef NODE list;
//初始化循环链表,前驱和后继都指向自身


plist init()
{
	list* head;
	head = (list*)malloc(sizeof(list));
	head->pier = head;
	head->pnext = head;
	return head;
}
plist lcreate(list* head)
{
	list* lend, *lnew;
	int num, i, data;
	lend = head;
	printf("需要输入多少位数据:");
	scanf_s("%d", &num);
	for (i = 0; i < num; i++)
	{
		printf("数据:");
		scanf_s("%d", &data);
		lnew = (list*)malloc(sizeof(list));
		if (lnew == NULL)
		{
			printf("新节点分配内存失败\n");
			exit(-1);
		}
		lnew->pier = NULL;
		lnew->pnext = NULL;
		lnew->data = data;
		if (head == NULL)
		{
			head = lnew;
			lend = head;
		}
		else
		{
			lnew->pier = lend;
			lend->pnext = lnew;
			lend = lnew;
		}

	}
	//造环
	head->pier = lend;
	lend->pnext = head;
	return head;
}
void prit(list* head)
{
	list* p;
	if (head == NULL)
	{
		printf("链表已被清除!\n");
		exit(-1);
	}
	p = head->pnext;

	if (p == NULL)
	{
		printf("空链表!\n");
		exit(-1);
	}
	while (p != head)
	{
		printf("%d ", p->data);
		p = p->pnext;
	}
}
void pierprit(list* head)
{
	list* p;
	p = head->pier;
	if (p->pier == NULL)
	{
		printf("空链表!\n");
		exit(-1);
	}
	while (p != head)
	{
		printf("%d ", p->data);
		p = p->pier;
	}
}

//删除指定节点
plist numdel(list* head, int num)
{
	list* p;
	int i = 1;
	p = head->pnext;
	if (p == NULL || num<0)
	{
		printf("链表为空或者输入节点不合法!\n");
		exit(-1);
	}
	while (ipnext;

	}

	p->pier->pnext = p->pnext;
	p->pnext->pier = p->pier;
	free(p);
	return head;

}
//销毁链表
plist destroylist(list* head)
{
	list* p, *p1;
	p = head->pnext;
	p1 = p;
	if (p == NULL)
	{
		printf("空链表!\n");
		exit(-1);
	}
	while (p != head)
	{
		p1 = p1->pnext;
		free(p);
		p = p1;
	}
	head = NULL;
	printf("链表销毁成功!\n");
	return head;
}
int main()
{
	list* temp = NULL;
	int delnum;
	temp = init();
	temp = lcreate(temp);
	prit(temp);
	printf("\n逆向打印!\n");
	pierprit(temp);

	printf("输入要删除的节点:");
	scanf_s("%d", &delnum);
	numdel(temp, delnum);
	prit(temp);
	printf("\n逆向打印!\n");
	pierprit(temp);
	temp = destroylist(temp);
	prit(temp);
	return 0;
}

编译环境vs2015

你可能感兴趣的:(C语言)