非常经典的链表逆序题目:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
//无需逆序
if(head == nullptr || k == 1) return head;
int cnt = 0;
//添加dummy结点,减少边界条件处理
ListNode* dummy = new ListNode(-1);
dummy->next = head;
//初始化相关指针
ListNode* prev = dummy;
ListNode* curr = prev->next,*nxt = nullptr;
//统计链表结点数量
while(curr)
{
curr = curr->next;
cnt++;
}
//每k个一组逆序
while(cnt >= k)
{
curr = prev->next;
nxt = curr->next;
for(int i = 1;i < k;i++)
{
//当前结点指向下下个结点
curr->next = nxt->next;
//下下个结点指向第一个结点
nxt->next = prev->next;
//更新第一个结点
prev->next = nxt;
//
nxt = curr->next;
}
//更新prev为前一个k组最后一个结点
prev = curr;
cnt -= k;
}
return dummy->next;
}
};
运行效率:
Runtime: 16 ms, faster than 78.74% of C++ online submissions for Reverse Nodes in k-Group.
Memory Usage: 11.6 MB, less than 54.73% of C++ online submissions for Reverse Nodes in k-Group.