LeetCode-25. K 个一组翻转链表(Reverse Nodes in k-Group)

和24题差不多,用一个指针记录前一个节点,需要特判,若count结束后并不等于k则翻转回来

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
    	ListNode *newHead = new ListNode(0);
    	ListNode *relativeHead = newHead;
    	ListNode *tail = newHead;
    	ListNode *p = head;
    	ListNode *pre = head;
    	int count = 0;
    	while(p) {
    		if(count == k || count == 0) {
    			relativeHead = tail;
    			tail = p;
    			count = 0;
    		}
    		pre = p;
    		p = p->next;
    		pre->next = relativeHead->next;
    		relativeHead->next = pre;
    		count++;
    	}
    	if(count != k){
    		p = relativeHead->next;
    		relativeHead->next = NULL;
    		while(p) {
    			pre = p;
    			p = p->next;
    			pre->next = relativeHead->next;
    			relativeHead->next = pre;
    		}
    	}
    	return newHead->next;      
    }
};

题目链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

你可能感兴趣的:(leetcode,leetcode,25,K个一组翻转链表,Reverse,Nodes,in,k-Group,C++)