2019年11月28日
LeetCode 25. Reverse Nodes in k-Group
C++, LeetCode, 算法, 编程
0 Comments
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.
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
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
解析:
分组翻转链表,根据给定的数值K,按照K分组进行逆序,如果最后剩余元素不足K,则保持原样。
考虑递归的方式处理,先把前K个元素单独拿出来,将这K的元素逆序,然后再与K元素之后的元素进行连接,后面的元素也是同样的处理。具体见代码注释。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//递归的方式进行链表翻转
ListNode* reverseByRecursion(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* new_list = reverseByRecursion(head->next);
head->next->next = head;
head->next = NULL;
return new_list;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* temp = head;
for (int i = 1; i < k && temp != NULL; i++)//先找到前K个元素 {
temp = temp->next;
}
if(temp == NULL)
return head;
ListNode *part_head = temp->next;
//后面元素
temp->next = NULL;
//前K的元素与后面元素的连接关系断掉,将前K的元素单独拿出来
ListNode *new_head = reverseByRecursion(head);
//前K个元素逆序
ListNode *new_temp = reverseKGroup(part_head, k);
//后面元素依次处理
head->next = new_temp;
//将翻转后的元素连接起来
return new_head;
}
}
;
运行结果:
