题目描述
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
解题思路:
先求出链表长度,计算出链表最多有几个k组,
然后依次翻转
pre | cur | nextnode | ....... | |
需要翻转的k段 |
这里需要特别注意:如何做到不断链翻转
额外引入pre节点
nextnode = cur->next;
cur->next = nextnode->next;
nextnode->next = pre->next;
pre->next = nextnode;
完整代码如下:
/**
* 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) {
int len = 0;
ListNode *tmp = new ListNode(0);
ListNode *prev = tmp;
ListNode *cur=head;
ListNode *nextnode;
tmp->next = head;
while(head){
len++;
head = head->next;
}
head = tmp->next;
int cnt = len/k;
if(cnt==0) return head;
for(int i=0;i<cnt;i++){
for(int j=0;j<k-1;j++){
nextnode = cur->next;
cur->next = nextnode->next;
nextnode->next = prev->next;
prev->next = nextnode;
}
prev = cur;
cur = prev->next;
}
return tmp->next;
}
};