Leetcode: Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

/**
 * 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 == NULL) {
            return NULL;
        }
        
        // In case k is bigger than the list length
        int list_length = 0;
        ListNode *tail = head;
        while (tail != NULL) {
            ++list_length;
            tail = tail->next;
        }
        k %= list_length;
        if (k == 0) {
            return head;
        }
        
        // Find the original list tail and the rotated list head
        tail = head;
        while (k > 0) {
            tail = tail->next;
            --k;
        }
        ListNode *new_head = head;
        while (tail->next != NULL) {
            tail = tail->next;
            new_head = new_head->next;
        }
        
        tail->next = head;
        head = new_head->next;
        new_head->next = NULL;
        
        return head;
    }
};

==============第二次=================

/**
 * 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 (k == 0 || head == NULL) {
            return head;
        }
        
        int count = 0;
        ListNode *cur = head;
        ListNode *tail = NULL;
        while (cur != NULL) {
            tail = cur;
            cur = cur->next;
            ++count;
        }
        
        k %= count;
        if (k == 0) {
            return head;
        }
        
        k = count - k;
        cur = head;
        while (--k > 0) {
            cur = cur->next;
        }
        ListNode *new_head = cur->next;
        cur->next = NULL;
        tail->next = head;
        
        return new_head;
    }
};


你可能感兴趣的:(LeetCode,链表)