leetcode_25题——Reverse Nodes in k-Group (链表)

Reverse Nodes in k-Group

  Total Accepted: 34390 Total Submissions: 134865My Submissions

 

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 as it is.

You may not alter the values in the nodes, only nodes 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

 

Hide Tags
  Linked List
Have you met this question in a real interview? 
Yes
 
      这道题可以采用一种循环递归的方法来做,每次逆序k个节点,然后对于后面的由于和前面的一样,所以可以采用递归的方法
#include<iostream>

using namespace std;





struct ListNode {

	int val;

	ListNode *next;

	ListNode(int x) : val(x), next(NULL) {}

};



ListNode* reverseKGroup(ListNode* head, int k) {

	if(k<=1||head==NULL)

		return head;

	ListNode *ptr0=head;

	ListNode *ptr1=head;

	ListNode *head1=NULL;

	ListNode *ptr2=NULL;



	int N=k-1;

	int flag=0;

	while(N--)

	{

		ptr1=ptr1->next;

		if(ptr1==NULL)

		{

			flag=1;

			break;

		}

	}

	if(flag==1)

		return ptr0;

	ptr2=ptr1->next;

	

	ListNode *ptr3=ptr0->next;

	if(ptr3==ptr1)

	{

		ptr1->next=ptr0;

		ptr0->next=reverseKGroup(ptr2,k);

		return ptr1;

	}

	ListNode *ptr4=NULL;

	ptr0->next=reverseKGroup(ptr2,k);

	while(1)

	{

		ptr4=ptr3->next;

		ptr3->next=ptr0;

		if(ptr4==ptr1)

			break;

		else

		{

			ptr0=ptr3;

			ptr3=ptr4;

		}		

	}

	ptr1->next=ptr3;

	return ptr1;

}



int main()

{



}

  

 

你可能感兴趣的:(LeetCode)