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.

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(!head) return head;
        
        ListNode *p = head;
        ListNode *newHead;
        int num = 1;
        while(p->next)
        {
            p = p->next;
            num++;
        }
        k = k%num;
        if(k==0) return head;
        p->next = head;
        p = head;
        for(int i = 0; i<num-k-1; i++)
        {
            p = p->next;
        }
        head = p->next;
        p->next = NULL;
        return head;
    }
};

 

相关文章:

  • 2021-08-30
  • 2021-10-10
  • 2021-08-02
  • 2021-11-16
  • 2021-06-27
  • 2021-06-04
  • 2022-03-03
猜你喜欢
  • 2021-05-03
  • 2021-07-17
相关资源
相似解决方案