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

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *rotateRight(ListNode *head, int k) {
12         if(head == nullptr || head->next == nullptr) return head;
13 
14         int length = 0;
15         ListNode* p = head;
16         while(p){
17             length++;
18             p = p->next;
19         }
20         k = k % length;
21         if(k == 0) return head;
22         int m = length - k;
23         p = head;
24         while(m > 1){
25             p = p->next;
26             m--;
27         }
28         ListNode* right = p->next;
29         p->next = nullptr;
30         p = right;
31         while(p->next){
32             p = p->next;
33         }
34         p->next = head;
35         head = right;
36         return head;
37     }
38 };

 

相关文章:

  • 2021-09-15
  • 2022-12-23
  • 2021-07-24
  • 2022-12-23
  • 2022-01-13
  • 2021-05-24
  • 2021-09-21
  • 2021-11-15
猜你喜欢
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案