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

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

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=117&tqId=37746&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
class Solution {
  public:
    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
	  	//特判
        if (head == nullptr || k == 1)
    	{
        return head;
    	}
        ListNode* slow, *fast = head;
        int cnt;
        // 虚拟头结点
        ListNode zero(0);
        zero.next = head;
        slow = &zero;
        head = slow;

        while (fast) {
            cnt = 1;
            // 循环向前
            while (cnt < k) {
                fast = fast->next;
                // fast到末尾了, 直接返回
                if (!fast) {
                    return zero.next;
                }
                cnt++;
            }
		  
            // 翻转
            ListNode* pre, *cur, *nxt, *nxt_fast, *nxt_slow;
            nxt_fast = fast->next;
            nxt_slow = slow->next;

            pre = slow->next;
            cur = pre->next;
            nxt = cur->next;

            slow->next = fast;
            pre->next = nxt_fast;

            while (cur != fast) {
                cur->next = pre;
                pre = cur;
                cur = nxt;
                nxt = nxt->next;
            }
            cur->next = pre;

            // 重设slow和fast
            slow = nxt_slow;
            fast = nxt_fast;
        }
        return zero.next;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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