leetcode25. Reverse Nodes in k-Group
class Solution {
public:
ListNode* reverseKGroup(ListNode* head,int k) {
int step = k;
ListNode *front = new ListNode(0);
front->next = head;
ListNode *tail = front;
vector<ListNode*> heads = {};
ListNode *lHead = front;
if(head==NULL){
return NULL;
}
if(k==0 || k==1) return head;
tail = tail->next;
while(tail!=NULL){
front->next= reverseListK(tail,k);
front = tail;
tail = tail->next;
}
return lHead->next;
}
ListNode* reverseListK(ListNode* &head,int k){
if(head==NULL){
return NULL;
}
ListNode *temp = head;
int j = k;
ListNode *h=NULL;
ListNode *cursor = head;
ListNode *tail = head;
while(temp!=NULL&&j>=1){
cursor = temp;
temp = temp->next;
j--;
}
if(j>=1){
h = head;
head = cursor;
return h;
}
cursor = head;
while(k>0 && head!=NULL){
head = head->next;
cursor->next = h;
h = cursor;
cursor = head;
k--;
}
if(k==0) tail->next = cursor;
head = tail;
return h;
}
};
本文解析了LeetCode上的第25题——按组翻转链表问题,并提供了完整的C++代码实现。该解决方案使用了辅助节点来简化边界条件处理,并通过迭代方式实现了每k个一组的链表节点翻转。
526

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



