single_list reverse with k

//1,2,3,4,5,6,7,8,9,10
//k == 3
//3,2,1,6,5,4,9,8,7,10
#include <stdio.h>
#include <vector>
struct _LIST_NODE
{
	int val = 0;
	_LIST_NODE* next = nullptr;
	_LIST_NODE() :val(0), next(nullptr) {}
	_LIST_NODE(int _val):val(_val),next(nullptr){}
};

void ShowList(_LIST_NODE* head) {
	while (head) {
		printf("%d ", head->val);
		head = head->next;
	}
	printf("\n");
}
auto ReverseListWith(_LIST_NODE* headList, _LIST_NODE* endList)
{
	//1->2->3->     nextOfEnds
	//nextofnext <- 1 <- 2 <- 3

	auto nextOfEnds = endList->next;
	auto moveHead = headList;
	auto nextList = moveHead->next;
	while (moveHead && moveHead != endList) {
		if (nextList) {
			auto nextOfNext = nextList->next;
			nextList->next = moveHead;
			moveHead = nextList;
			nextList = nextOfNext;
		}
	}
	headList->next = nextOfEnds;
	return endList;
}
_LIST_NODE* ReverseListWithK(_LIST_NODE* head, int k)
{
	if (!head || k == 1) return head;
	auto newHead = head;
	bool bFirst = true;
	_LIST_NODE* currentMoveHead = head;
	int currentK = k;
	auto currentKHead = head;
	_LIST_NODE* preEnd = nullptr;
	while (currentKHead)
	{
		auto currentMoveHead = currentKHead;
		currentK = k-1;
		while (1) {
			if (!currentMoveHead) return newHead;
			currentMoveHead = currentMoveHead->next;
			--currentK;
			if (currentK == 0) {
				if (currentMoveHead->next) {
					auto _next = currentMoveHead->next;
					// 1->2->3->4
					// 3->2->1->4
					if (bFirst) {
						newHead = ReverseListWith(currentKHead, currentMoveHead);
						bFirst = false;
					}
					else {
						ReverseListWith(currentKHead, currentMoveHead);
					}
					if (preEnd) {
						preEnd->next = currentMoveHead;
					}
					ShowList(newHead);

					preEnd = currentKHead;
					currentKHead = _next;
					break;
				}
				else {
					return newHead;
				}
			}
		}
	}
}
auto getEndList(_LIST_NODE* head) {
	auto pre = head;
	while (head) {
		pre = head;
		head = head->next;
	}
	return pre;
}
int main()
{
	std::vector<int> vecTest = {1,2,3,4,5,6,7,8,9,10 };
	auto head = new _LIST_NODE(vecTest[0]);
	auto listMove = head;
	for (int i = 1; i < vecTest.size(); ++i) {
		listMove->next = new _LIST_NODE(vecTest[i]);
		listMove = listMove->next;
	}

	int k = 5;
	ShowList(ReverseListWithK(head, k));
	printf("end\n");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值