Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4d0d611

Browse files
Create Rotate List
1 parent 5849641 commit 4d0d611

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

‎Top Interview 150/Rotate List

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
想法:先走過一次 list 算出總共長度 size , 實際上 k 等價於 k % size 的 rotate 次數;
2+
因為每次 rotate 是把最後一個元素放到最前面,所以 k 次 rotate 等價於 n - k 次把最前面的元素放到最後
3+
因此,我們只需執行 n - k 次將頭部放到尾部的操作即可
4+
5+
// assume there are n nodes in list
6+
Time Complexity : O(n) for traversing the list
7+
Space Complexity : O(1) for variables
8+
9+
/**
10+
* Definition for singly-linked list.
11+
* struct ListNode {
12+
* int val;
13+
* ListNode *next;
14+
* ListNode() : val(0), next(nullptr) {}
15+
* ListNode(int x) : val(x), next(nullptr) {}
16+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
17+
* };
18+
*/
19+
class Solution {
20+
public:
21+
ListNode* rotateRight(ListNode* head, int k) {
22+
if ( !head )
23+
return nullptr ;
24+
25+
ListNode* cursor = head , *tail ;
26+
int size = 0 ;
27+
28+
while (cursor) {
29+
size++ ;
30+
tail = cursor ;
31+
cursor = cursor->next;
32+
}
33+
34+
k %= size ;
35+
if (k == 0)
36+
return head ;
37+
k = size - k ;
38+
while ( k-- ) {
39+
ListNode* newtail = head , *newhead = head->next ;
40+
tail->next = newtail ;
41+
newtail->next = nullptr ;
42+
tail = newtail ;
43+
head = newhead ;
44+
}
45+
return head;
46+
}
47+
};
48+
49+
// 法二:一樣先找出等價的 k <= n ,接著把尾部與頭部相連,再把第 n - k - 1 個(0-index)元素設成尾部
50+
輸出第n - k 個元素即可
51+
/**
52+
* Definition for singly-linked list.
53+
* struct ListNode {
54+
* int val;
55+
* ListNode *next;
56+
* ListNode() : val(0), next(nullptr) {}
57+
* ListNode(int x) : val(x), next(nullptr) {}
58+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
59+
* };
60+
*/
61+
class Solution {
62+
public:
63+
ListNode* rotateRight(ListNode* head, int k) {
64+
if ( !head )
65+
return nullptr ;
66+
67+
ListNode* cursor = head , *tail ;
68+
int size = 0 ;
69+
70+
while (cursor) {
71+
size++ ;
72+
tail = cursor ;
73+
cursor = cursor->next;
74+
}
75+
76+
k %= size ;
77+
if (k == 0)
78+
return head ;
79+
tail->next = head ;
80+
cursor = head ;
81+
k = size - k ;
82+
while (--k) {
83+
cursor = cursor->next ;
84+
}
85+
ListNode* newhead = cursor->next ;
86+
cursor->next = nullptr;
87+
return newhead ;
88+
}
89+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /