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 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答思路:
这道题让我们以每k个为一组来翻转链表,实际上是把原链表分成若干小段,然后分别对其进行翻转,那么肯定总共需要两个函数,一个是用来分段的,一个是用来翻转的,我们就以题目中给的例子来看,对于给定链表 1->2->3->4->5,一般在处理链表问题时,我们大多时候都会在开头再加一个 dummy node,因为翻转链表时头结点可能会变化,为了记录当前最新的头结点的位置而引入的 dummy node,那么我们加入 dummy node 后的链表变为 -1->1->2->3->4->5,如果k为3的话,我们的目标是将 1,2,3 翻转一下,那么我们需要一些指针,pre 和 cur->next分别指向要翻转的链表的前后的位置,cur指的是当前节点,然后翻转后 pre 的位置需更新为新一段链表的前一个位置。
-1->1->2->3->4->5 -> -1->2->1->3->4->5 -> -1->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)
{
if(head == NULL || k == 0) return NULL;
if(k == 1) return head ;
ListNode* header = new ListNode(-1) ;
header->next = head ;
ListNode *pre = header , *cur = head ; //还犯这种复合类型的错误。
for(int i = 1 ; cur ; i++)
{
if(i % k == 0)
{
pre = reverse(pre , cur->next) ;
cur = pre->next ;
cout<<"if i=="<<i<<endl;
}
else
{
cur = cur->next ;
cout<<"else i=="<<i<<endl;
}
}
return header->next ;
}
ListNode* reverse(ListNode* header , ListNode* trailer)
{
ListNode *last = header->next , *cur = last->next ;
while(cur != trailer)
{
last->next = cur->next ;
cur->next = header->next ;
header->next = cur ;
cur = last->next ;
}
return last ;
}
};