-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotate_List.cpp
More file actions
67 lines (57 loc) · 1.35 KB
/
Rotate_List.cpp
File metadata and controls
67 lines (57 loc) · 1.35 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Source : https://oj.leetcode.com/problems/rotate-list/
// Author : zheng yi xiong
// Date : 2015-02-05
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (0 == k || NULL == head)
{
return head;
}
ListNode *pNode = head, *pRotate = head;
int len = 1;
while (pNode->next) {
len++;
pNode = pNode->next;
}
k = len - k % len;
pNode->next = head;
for(int step = 0; step < k; step++) {
pNode = pNode->next;
}
head = pNode->next;
pNode->next = NULL;
return head;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ListNode node1(1);
ListNode node2(2);
ListNode node3(3);
ListNode node4(4);
ListNode node5(5);
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
Solution so;
ListNode *pHead = so.rotateRight(&node1, 2);
return 0;
}