Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain asit is.

You may not alter the values in the nodes, onlynodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list:
 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

 

       思路:本题要求空间复杂度为O(1),因此不能用栈来翻转k个元素。所以,本题真正的难点在于,如何用有限的指针,实现链表中k个元素的翻转。代码如下:

struct ListNode *reverseknode(struct ListNode *begin, int k)
{
	struct ListNode *endnext = begin;
	while(k && endnext)
	{
		k--;
		endnext = endnext->next;
	}
	if(k > 0)	return begin;

	struct ListNode *reshead = endnext;
	struct ListNode *p, *q;
	p = begin;

	while(p != endnext)
	{
		q = p->next;
		p->next = reshead;
		reshead = p;
		p = q;
	}

	return reshead;
	
}
struct ListNode* reverseKGroup(struct ListNode* head, int k) 
{
	struct ListNode *reshead, *p, *q, *r;

	reshead = NULL;
	p = head;

	while(p != NULL)
	{
		q = reverseknode(p, k);

		if(reshead == NULL)	reshead = q;
		else r->next = q;

		if(p == q)	break;

		r = q;
		while(r != p)
		{
			r = r->next;
		}
		p = p->next;
	}
	return reshead;
}

  


原文地址:https://www.cnblogs.com/gqtcgq/p/7247150.html