题解 | #链表中的节点每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类
*/
void reverse(ListNode* list){
ListNode* pre = nullptr, *cur = list, *next;
while(cur){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || k == 1) return head;
// write code here
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy, *cur = head, *next = cur, *next_head;
while(next->next){
for(int i = 1; i < k; i++){
if(next->next){
next = next->next;
}else{
return dummy->next;
}
}
next_head = next->next;
pre->next = nullptr;
next->next = nullptr;
reverse(cur);
//connect
pre->next = next;
cur->next = next_head;
//change
pre = cur;
cur = next_head;
next = cur;
if(cur == nullptr) break;
}
return dummy->next;
}
};