题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
  	// write code here
		if(!head || !head->next || k <= 1) return head;

		ListNode* ret = head;
		int Count = k;
		while (--Count) { if(!ret) return head;	ret = ret->next;}
		if(!ret) return head;
		Count = 0;
		ListNode* Pre = nullptr,*Phead = head, *temp = nullptr;
		while (Phead) {
			// Find PtrNext 
			if (!Count) {
				Pre = Phead;
				for(int i=0; i< k; i++) {

					if(!Pre) return ret;

					Pre = Pre->next;
				}
				temp = Pre;

				for(int i=1; i< k;i++){
					if(!Pre) {Pre = temp; break;}
					Pre = Pre->next;
				}
				if(!Pre) Pre = temp;
				Count = k;
				
			}

			temp = Phead->next;
			Phead->next = Pre;
			Pre = Phead;
			Phead = temp;
			Count--;



		}
			
		return ret;



	}
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务