题目
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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
解析
/
**
* 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) {
ListNode
*p=head;
int len=
0;
while(p){
len++;
p=p->
next;
}
ListNode
*dummy=new ListNode(-
1);
p=dummy;
ListNode
*q=head;
int pos=
0;
while(
q){
int m=
0;
if(
pos+k>len){
//剩余的元素的个数小于k个时,直接将剩余的元素插入到当前链表尾部后返回
p->
next=
q;
break;
}
while(
m<k){
//对于每个分组中的k个元素,采用头插的方式
ListNode
*temp=
q;
q=
q->
next;
temp->
next=p->
next;
p->
next=temp;
m++;
}
while(p->
next){
//将待插入的位置已完成逆序的最后一个元素
p=p->
next;
}
pos+=k;
}
return dummy->
next;
}
};