力扣61.旋转链表

力扣61.旋转链表_第1张图片

    int sum(ListNode* head){// 封装计算节点数的函数
        int len = 0;
        while (head != nullptr) {
            head = head->next;
            len++;
        }
        return len;
    }
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr || head->next == nullptr || k == 0) return head;
        ListNode* fast = head;
        ListNode* slow = head;

        // 计算链表中节点个数
        int len = sum(head);
        k = k % len;

        while(fast != nullptr && k--){//fast先走k步
            fast = fast->next;
        }
        while (fast != NULL && fast->next != nullptr) {//fast,slow一起走
		    fast = fast->next;
		    slow = slow->next;
	    }
        fast->next = head;//连成环
        head = slow->next;//新头结点
        slow->next = nullptr;//断链
        return head;
    }

你可能感兴趣的:(leetcode,链表,算法)