题解 | #链表中的节点每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;



	}
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 11:30
点赞 评论 收藏
分享
zhch7:建议9✌️把学历加黑加粗,如果实在offer可能是觉得佬不会去
投了多少份简历才上岸
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 17:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务