递归法跟压栈法,没想出来,都是copy的大佬的创意,不过看懂了。
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode* newHead = new ListNode(0);
ListNode* p = newHead;
stack<ListNode *>store;
while(true){
ListNode* tmp = head;
bool flag = false;
for(int i=0;i<k;i++){
if(tmp == NULL){
p->next = head;
flag = true;
break;
}
store.push(tmp);
tmp = tmp->next;
}
if(flag){
break;
}
while(!store.empty()){
p->next = store.top();
p = p->next;
store.pop();
}
head = tmp;
}
return newHead->next;
}
};
/**
* 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 *tail = head;
for (int i = 0; i < k; i++) {
if(tail == NULL){
return head;
}
tail = tail->next;
}
ListNode *newHead = revertList(head, tail);
head->next = reverseKGroup(tail, k);
return newHead;
}
ListNode* revertList(ListNode *start,ListNode *end){
ListNode *pre = NULL;
ListNode *next = NULL;
while(start != end){
next = start->next;
start->next = pre;
pre = start;
start = next;
}
return pre;
}
};



京公网安备 11010502036488号