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
以K个元素为一组,翻转链表。
那就写一个reverse方法,每K个元素,一翻转就好了。这里有一个问题,要把翻转后的链表连起来,就要记录每一段K个元素链表翻转前后的收尾地址。这样无疑会增加代码的复杂度,因为要有很多指针。这里我用一个pair类型作为reverse的返回值,pair.first表示头指针,pair.second表示尾指针。
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *start = head, *tmp = head, *newHead = NULL, *end = NULL;
int count = 1;
while (tmp != NULL){
if (count == k){
tmp = tmp->next;
count = 1;
pair<ListNode *, ListNode *> p = reverse(head,k);
if (!newHead){
newHead = p.first;
end = p.second;
}
else{
end->next = p.first;
end = p.second;
}
head = tmp;
}
if (tmp){
tmp = tmp->next;
count++;
}
}
if (newHead){
end->next = head;
return newHead;
}
else{
return head;
}
}
pair<ListNode *, ListNode *> reverse(ListNode *head, int k){
pair<ListNode *, ListNode *> p;
ListNode *last = head, *now = head, *end = head, *next;
for (int i = 0; i < k; i++){
next = now->next;
now->next = last;
last = now;
now = next;
}
p.first = last;
p.second = end;
return p;
}
};
3228

被折叠的 条评论
为什么被折叠?



