【数据结构基础整理】线性表--02:双向链表操作集

0x01.结构

typedef struct SLIST
{
	int data;
	struct SLIST * next;
	struct SLIST* front;
}SLIST;

SLIST* head=NULL;//全局指针
SLIST* end = NULL;

0x02.创建

void CreateList()
{
	head = (SLIST*)malloc(sizeof(SLIST));
	head->next = head->front = NULL;
	end = NULL;
}

0x03.增

void AddData(int m)
{
	if (head == NULL)
	{
		printf("头结点为空,无法插入!!!");
		return;
	}
	SLIST* tmphead = head;
	if (tmphead->next == NULL)//当只有一个头结点的时候
	{
		SLIST* pnew = (SLIST*)malloc(sizeof(SLIST));
		pnew->data = m;
		pnew->next = tmphead->next;//核心代码
		tmphead->next = pnew;
		pnew->front = tmphead;
		end=pnew;
	}
	else
	{
		SLIST* pnew = (SLIST*)malloc(sizeof(SLIST));
		pnew->data = m;
		/*tmphead->next->front = pnew;//核心代码
		pnew->front = tmphead;
		pnew->next = tmphead->next;
		tmphead->next = pnew;
		*/
		end->next = pnew;
		pnew->front = end;
		pnew->next = NULL;
		end=end->next;	
		
	}
}

0x04.删

void DeleteData(int m)
{
	if (head == NULL)
	{
		printf("链表为空!!!");
		return;
	}
	SLIST* tmphead = head;
	while (tmphead->next != NULL)
	{
		tmphead = tmphead->next;
		if (tmphead->data == m)
		{
			tmphead->front->next = tmphead->next;//核心代码
			tmphead->next->front = tmphead->front;//
			break;
		}
	}
	free(tmphead);
	return;
}

0x05.遍历

void PrintData()
{
	if (head == NULL)
	{
		printf("链表为空!!!");
		return;
	}
	SLIST* tmphead = head;
	printf("正向输出结果:\n");
	while (tmphead->next != NULL)
	{
		tmphead = tmphead->next;
		printf("%d\n", tmphead->data);
	}
	//从尾开始遍历
	printf("反向输出结果:\n");
	while (tmphead->front->front != NULL)
	{
		printf("%d\n", tmphead->data);
		tmphead = tmphead->front;
	}
	printf("%d\n", tmphead->data);
	return;
}

0x06.主函数测试

int main()
{
	int n,i,m;
	CreateList();
	printf("你想为双向链表添加几个元素???");
	scanf("%d", &n);
	for (i = 0; i < n; i++)
	{
		printf("\n添加第 %d 个元素: 为多少?",i+1);
		scanf("%d", &m);
		AddData(m);
	}
	printf("添加完毕!!!\n");
	PrintData();
	printf("你想删除的元素的值为多少?");
	scanf("%d", &m);
	DeleteData(m);
	PrintData();

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ATFWUS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值