LetCode 61. 旋转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL || head->next == NULL || k == 0)
            return head;
        int len = 0;
        ListNode* ptr = head;
        ListNode* last = NULL;
        while(ptr != NULL){
            last = ptr;
            len++;
            ptr = ptr->next;
        }
        k %= len;
        if (k == 0)
            return head;
        ptr = head;
        for (int i = 0; i < len - k - 1; i++)
            ptr = ptr->next;
        ListNode* void_node = new ListNode(0);
        void_node->next = ptr->next;
        last->next = head;
        ptr->next = NULL;
        return void_node->next;        
    }
};

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/81004614