Rotate List Solutions in C++
Number 61
Difficulty Medium
Acceptance 30.1%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/rotate-list/// Author : Hao Chen// Date : 2014-06-20/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public:ListNode *rotateRight(ListNode *head, int k) {if (!head || k<=0){return head;}//find the length of Listint len=1;ListNode *p=head;while( p->next != NULL ){p = p->next;len++;}//connect the tail to headp->next = head;//find the left place (take care the case - k > len)k = len - k % len;//find the placefor(int i=0; i<k; i++){p = p->next;}//break the listhead = p->next;p->next = NULL;return head;}};
C++ solution by pezy/LeetCode
#include <cstddef>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode *rotateRight(ListNode *head, int k) {if (head == NULL || k == 0) return head;ListNode *slow = head, *fast = head;while (k--) {if (fast == NULL) fast = head;fast = fast->next;}if (fast == NULL) return head;while (fast->next) {fast = fast->next;slow = slow->next;}ListNode *new_head = slow->next;slow->next = NULL;fast->next = head;return new_head;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/rotate-list/description//// Author : liuyubobobo/// Time : 2018-03-18#include <iostream>using namespace std;// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/// Brute Force/// Two Pointers////// Time Complexity: O(N)/// Space Complexity: O(1)class Solution {public:ListNode* rotateRight(ListNode* head, int k) {if(head == NULL)return NULL;int len = get_len(head);k = k % len;ListNode* end = head;for(int i = 0 ; i < k ; i ++)end = end->next;ListNode* start = head;while(end->next != NULL){start = start->next;end = end->next;}end->next = head;head = start->next;start->next = NULL;return head;}private:int get_len(ListNode* head){int res = 0;while(head){res ++;head = head->next;}return res;}};int main() {return 0;}