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
解:这一题呢延续一贯的思路可以用分治的思想,主要的问题还是按照k个元素进行分,然后治呢就是要reverse每个分组的元素节点,难点还是在于reverse函数。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode*head, ListNode* node){
ListNode* new_head = node;
while(head != node){
ListNode* tmp = head->next;
head->next = new_head;
new_head = head;
head = tmp;
}
return new_head;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* node = head;
for(int i = 0; i < k; ++i){
if(node == NULL) return head;
node = node->next;
}
ListNode* new_head = reverse(head, node);
head->next = reverseKGroup(node, k);
return new_head;
}
};
本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。讨论了如何在不改变节点值的情况下仅改变节点本身来实现此操作,同时确保内存使用保持常数。
447

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



