链表中的节点每k个一组翻转_牛客题霸_牛客网 (nowcoder.com)

/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
//找到每次翻转的尾部
ListNode* tail = head;
//遍历k次到尾部
for(int i = 0; i < k; i++){
if(tail == nullptr) return head;
tail = tail->next;
}
//双指针
ListNode* pre = nullptr;
ListNode* cur = head;
//遍历
while(cur != tail){
ListNode* temp = cur ->next;
cur->next = pre;
pre = cur;
cur = temp;
}
//当前尾指向下一段要翻转的链表
head->next = reverseKGroup(tail,k);
return pre;
}
};
305

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



