Leetcode 0025. Reverse Nodes in k-Group

时间:2023-03-09 19:56:05
Leetcode 0025. Reverse Nodes in k-Group
居然把头插法写错了,debug了一个多小时
/**
* 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(k == || head == nullptr) return head;
ListNode *tail = head;
int i;
for(i=;i<k && tail != nullptr;i++,tail=tail->next);
if(i<k) return head;
tail = reverseKGroup(tail, k);
ListNode* rear = head,*tmp=nullptr;
head= tail;
for(int i = ;i<k;i++){
tmp = rear->next;
rear->next = head;
head = rear;
rear = tmp;
}
return head;
}
};