/**
* 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)
{
ListNode* newHead=new ListNode(-1);
newHead->next=head;
ListNode* tail=newHead;
ListNode* begin=head;
ListNode* end=head;
while(true)
{
int count=k;
while(count && end!=NULL)
{
end=end->next;
--count;
}
if(count==0)
{
stack<ListNode* >s;
while(begin!=end)
{
s.push(begin);
begin=begin->next;
}
while(!s.empty())
{
ListNode* temp=s.top();
tail->next=temp;
s.pop();
tail=tail->next;
}
}
else
{
tail->next=begin;
break;
}
}
return newHead->next;
}
};
Reverse Nodes in k-Group
最新推荐文章于 2022-04-08 22:28:12 发布