您的位置:首页 > Web前端 > Node.js

LeetCode Reverse Nodes in k-Group

2014-05-21 15:55 357 查看
题目

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


就是上一个问题的扩展,把2变成了k。

由于空间限制为常数级,所以每次取k个数(仅记录开始位置和下次要开始的位置),依次向后记录必要信息并修改即可

代码:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(k<=1)
return head;
ListNode *pro=NULL,*next=head,*p1=head,*p2;	//前一组k个数调整后的尾,待调整的数,调整用的两个临时数
int i;
while(next!=NULL)
{
for(i=0;i<k-1;i++)	//寻找一组k个数,结束后next指向这组数的最后一个
{
next=next->next;
if(next==NULL)
break;
}
if(i<k-1)	//找不到
return head;
else		//找得到
{
if(pro!=NULL)	//不是第一组k个数
{
pro->next=next;
pro=p1;
}
else			//是第一组,处理头
{
pro=head;
head=next;
}
next=next->next;	//将next指向再下一个
for(i=0;i<k;i++)	//循环修改k个数,结束后p1指向下一个数
{
p2=p1->next;
p1->next=next;
next=p1;
p1=p2;
}
next=p1;	//修改next
}
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: