这题懵逼的做出来了,懵在最后如何返回链表首节点,凭着感觉写了个dummy,结果就AC了,过了之后想半天没想明白怎么就AC了?在VS上调试发现是pre的功劳。首次进if时pre仍代表dummy,把dummy更新了。真是无心插柳。
/**
* 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) {
stack<ListNode*> s;
int cnt = 0;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy;
while(head)
{
cnt++;
if(cnt == k)
{
cnt = 0;
ListNode *tail = head -> next;
pre->next = head;//**关键**
while(!s.empty())
{
ListNode *next = s.top();
head->next = next;
head = head ->next;
s.pop();
}
head ->next = tail;
pre = head;
}
else
{
s.push(head);
}
head = head->next;
}
return dummy->next;
}
};