双向循环链表(无头)

思路:定义一个头指针,作用是时刻指向新加入的节点(特别针对头添加来说的话),而且不需要中间变量来记录头指针的位置,任何一个数据都可以直接或者间接用头指针找到。

尾添加:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
	int data;
	struct node* pnext;
	struct node* ppore;
};


void endadd(struct node** phead, int adddata);

int main(void)
{
	struct node* phead = NULL;
	endadd(&phead, 8);

	return 0;
	system("pause>0");
}
void endadd(struct node** phead, int adddata)
{
	struct node* ptemp = (struct node*)malloc(sizeof(struct node));
	if (NULL == ptemp)
		return;
	ptemp->data = adddata;
	ptemp->pnext = NULL;
	ptemp->ppore = NULL;
	if (NULL == *phead)
	{
		ptemp->pnext = ptemp;
		ptemp->ppore = ptemp;
		(*phead) = ptemp;

	}
	else
	{
		ptemp->pnext = (*phead);
		ptemp->ppore = (*phead)->ppore;
		
		//后断
		
		(*phead)->ppore->pnext = ptemp;
		(*phead)->ppore = ptemp;
	}



}

那么对于头添加,只需要使用头指针时刻指向新节点((*phead) = ptemp);

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
	int data;
	struct node* pnext;
	struct node* ppore;
};


void headadd(struct node** phead, int adddata);

int main(void)
{
	struct node* phead = NULL;
	headadd(&phead, 5);
	headadd(&phead, 6);
	headadd(&phead, 4);
	headadd(&phead, 9);
	headadd(&phead, 8);

	return 0;
	system("pause>0");
}
void headadd(struct node** phead, int adddata)
{
	struct node* ptemp = (struct node*)malloc(sizeof(struct node));
	if (NULL == ptemp)
		return;
	ptemp->data = adddata;
	ptemp->pnext = NULL;
	ptemp->ppore = NULL;
	if (NULL == *phead)
	{
		ptemp->pnext = ptemp;
		ptemp->ppore = ptemp;
		

	}
	else
	{
		ptemp->pnext = (*phead);
		ptemp->ppore = (*phead)->ppore;
		
		//后断
		
		(*phead)->ppore->pnext = ptemp;
		(*phead)->ppore = ptemp;
		
	}
    (*phead) = ptemp;


}

猜你喜欢

转载自blog.csdn.net/weixin_72906726/article/details/129602517
今日推荐