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 85b06a0

Browse files
author
fupengfei058
committed
1/31 COMMIT
1 parent 20bf2ea commit 85b06a0

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎Leetcode/61. Rotate List.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*Rotate List:Given a list, rotate the list to the right by k places, where k is non-negative.*/
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* ListNode *next;
7+
* ListNode(int x) : val(x), next(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
ListNode* rotateRight(ListNode* head, int k) {
13+
if(head == NULL || k <= 0){
14+
return head;
15+
}
16+
int count = 1;
17+
ListNode *pre = head,*cur;
18+
//统计节点个数,找到尾节点串成一个环
19+
while(pre->next != NULL){
20+
count++;
21+
pre = pre->next;
22+
}
23+
//串成一个环
24+
pre->next = head;
25+
//k可能大于链表长度
26+
k = k % count;
27+
int index = 1;
28+
pre = cur = head;
29+
//右移k位
30+
while(index <= (count - k)){
31+
pre = cur;
32+
cur = cur->next;
33+
index++;
34+
}
35+
//新的首尾节点
36+
pre->next = NULL;
37+
head = cur;
38+
return head;
39+
}
40+
};

0 commit comments

Comments
(0)

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