/
RotateList.cpp
52 lines (48 loc) · 1.01 KB
/
RotateList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
*Rotate List
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
*/
#include<iostream>
#include<math.h>
#include<vector>
#include<stdlib.h>
using namespace std;
/**
* 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 head;
int nodeSize = 0;
vector<ListNode*> vec;
ListNode* node = head;
while(node!=NULL){
vec.push_back(node);
node=node->next;
}
nodeSize = vec.size();
k = k % nodeSize;
if(k==0)
return head;
head = NULL;
for(int i=0;i<k;++i){
node = vec[nodeSize-1-i];
if(i==0)
node->next = vec[0];
else
node->next = head;
head = node;
}
node = vec[nodeSize-1-k];
node->next = NULL;
return head;
}
};