码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-21 17:14:03      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

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_25题——Reverse Nodes in k-Group (链表)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4592114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!