61. 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.

刚开始没看懂题意,不知道旋转的k是怎么定义的,后来看了别人的博客才知道,需要旋转的次数kk = k%len(list).因此得到以下自己编写的答案:

接下来就是两个指针之间相差K,是 求链表中倒数第k个数 的变形。


/**
 * 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|| head->next == NULL)
            return head;
        int sum = 0;
        ListNode* p = head;
        ListNode* p1 = head, *p2 = head;
        while(p){
            ++sum;
            p = p->next;
        }
        p = head;
        int kk = k % sum;
        if(kk == 0)
            return head;
            else{
            while(kk--)
                p2 = p2->next;
            while(p2->next != NULL){
                p1 = p1->next;
                p2 = p2->next;
            }
            p2->next = head;
            head = p1->next;
            p1->next= NULL;
            return head;
        }
    }
};


你可能感兴趣的:(LeetCode,C++,linklist,point,Two)