题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
* 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 *curr=head;
int total=0;
if(head==nullptr||k<=1)return head;
while(curr!=nullptr)
{
curr=curr->next;
total++;
}
curr=head;
if(total<k)return head;
//进入正文
stack<ListNode*>st;
int remains=total%k;
bool first=true;
int counter=0;
ListNode *pHead;
ListNode *pHead_curr;
for(int i=1;i<=total;i++)
{
if(counter<k)
{
ListNode* node=curr->next;
curr->next=nullptr;
st.push(curr);
curr=node;
counter++;
}
if(counter==k)
{
if(first)
{
pHead=st.top();
pHead_curr=st.top();
st.pop();
counter--;
first=false;
}
while(counter>0)
{
pHead_curr->next=st.top();
pHead_curr=pHead_curr->next;
st.pop();
counter--;
}
}
}
if(counter==0)return pHead;
stack<ListNode*>st2;
while(!st.empty())
{
st2.push(st.top());
st.pop();
}
while(!st2.empty())
{
pHead_curr->next=st2.top();
st2.pop();
pHead_curr=pHead_curr->next;
}
return pHead;
}
};