BM3 链表中的节点每k个一组翻转

描述
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
在这里插入图片描述

示例1

输入: {1,2,3,4,5},2
返回值: {2,1,4,3,5}

示例2

输入: {},1
返回值: {}

思路:
先反转一组(反转链表),然后使用递归反转剩下的。
递归三段式:
确定递归函数的参数和返回值
确定终止条件
确定单层递归的逻辑
1、每次进入函数的头节点遍历链表k次,分出一组,若是后续不足K个节点,不用反转直接返回头

	ListNode3* tail = head;
	for (int i = 0; i < k; i++)
	{
		if (tail == NULL)return head;
		tail = tail->next;
	}

2、将分出来的链表反转
3、链表反转后,原来的头变成了尾,后面接下一组的反转结果,下一组采用上述递归继续

	ListNode3* res = reverseList(head,tail);
	head->next = reverseKGroup(tail, k);

完整代码

#include<iostream>
using namespace std;

struct ListNode3{
	int val;
	ListNode3* next;
	ListNode3(int x=0):val(x),next(NULL){}
};

ListNode3* createList()
{
	ListNode3* dummy = new ListNode3();
	ListNode3* temp = NULL;
	ListNode3* tail = dummy;
	int a = 0;
	while (true)
	{
		cin >> a;
		temp = new ListNode3(a);
		tail->next = temp;
		tail = tail->next;
		if (cin.get() == '\n')
			break;
	}
	return dummy->next;
}

void printList(ListNode3* head)
{
	ListNode3* cur = head;
	while (cur)
	{
		cout << cur->val << ',';
		cur = cur->next;
	}
	cout << endl;
}

ListNode3* reverseList(ListNode3* left,ListNode3* right)
{
	ListNode3* pre = NULL;
	ListNode3* cur = left;
	while (cur!= right)
	{
		ListNode3* temp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = temp;
	}
	return pre;

}

ListNode3* reverseKGroup(ListNode3* head, int k)
{
	ListNode3* tail = head;
	for (int i = 0; i < k; i++)
	{
		if (tail == NULL)return head;
		tail = tail->next;
	}
	ListNode3* res = reverseList(head,tail);
	head->next = reverseKGroup(tail, k);
	return res;

}

int main()
{
	int k = 0;
	while(true)
	{
		ListNode3* head = createList();
		cin >> k;
		ListNode3* res = reverseKGroup(head, k);
		printList(res);
     }
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值