链表循环保留M个节点 然后删除N个节点 重复操作到链表尾部

本文展示了如何从原始代码中精简并优化链表操作的实现,重点关注了链表节点的创建、初始化和链表元素的移动,通过减少不必要的变量使用和简化流程来提高代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先给出一个写的比较差的版本:

#include <iostream>

struct node
{
	int data;
	node* next;
	node(int eData, node* eNext)
	{
		data = eData;
		next = eNext;
	}
};


void processLL(node** head, int m, int n)
{
	if(!head)
		return;

	node* cur = *head;
	int cntM = 1;
	int cntN = 1;
	node* prev = NULL;
	bool isM = true;
	while(cur)
	{
		if(isM)
		{
			if(cntM == 1 && prev)
			{
				prev->next = cur;
			}
			if(cntM == m)
			{
				prev = cur;
				isM = false;
				cntM = 1;
			}
			else
				cntM++;
			cur = cur->next;
		}
		else
		{
			if(cntN == n)
			{
				isM = true;
				cntN = 1;
			}
			else
				cntN++;
			node* tmp = cur;
			cur = cur->next;

			delete tmp;

			if(!cur && prev)
			{
				prev->next = NULL;
				break;

			}
		}
	}

};


void init(node** head, int n)
{
	node* cur = NULL;
	for(int i = 1; i <= n; i++)
	{
		if(!*head)
		{
			*head = new node(i, NULL);
			cur = *head;
		}
		else
		{
			cur->next = new node(i, NULL);
			cur = cur->next;
		}
	}
};




int main()
{
	node* head;
	head = NULL;
	init(&head, 10);
	processLL(&head, 2, 3);

	return 0;
}



下面是一个精简后的版本 这道问题不难 主要是要考虑全面 代码清晰

#include <iostream>

struct node
{
	int data;
	node* next;
	node(int eData, node* eNext)
	{
		data = eData;
		next = eNext;
	}
};


void processLL(node** head, int m, int n)
{
	if(!head)
		return;

	node* cur = *head;
	int cnt = 1;

	node* prev = NULL;
	while(true)
	{
		cnt = 1;
		while(cnt <= m)
		{
			if(cnt == 1 && prev)
				prev->next = cur;
			if(cnt == m)
				prev = cur;
			
			cnt++;
			cur = cur->next;

			if(!cur)
				return;
		}

		cnt = 1;
		while(cnt <= n)
		{
			cnt++;

			node* tmp = cur;
			cur = cur->next;
			delete tmp;

			if(!cur && prev)
			{
				prev->next = NULL;
				return;
			}
		}
	}
};


void init(node** head, int n)
{
	node* cur = NULL;
	for(int i = 1; i <= n; i++)
	{
		if(!*head)
		{
			*head = new node(i, NULL);
			cur = *head;
		}
		else
		{
			cur->next = new node(i, NULL);
			cur = cur->next;
		}
	}
};




int main()
{
	node* head;
	head = NULL;
	init(&head, 10);
	processLL(&head, 1, 3);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值