leetcode之Rotate List
2013-09-18 08:59
330 查看
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head==NULL||k<0) {
return head;
}
ListNode* end=head;
int len=1;
while(end->next) {
end=end->next;
len++;
}
if (k>=len) {
k=k%len;
}
if (k==0) {
return head;
}
ListNode* pos=head;
ListNode* pr=head;
while(pos&&k>0) {
k--;
pos=pos->next;
}
if (k>0) {
return head;
}
while(pos->next) {
pos=pos->next;
pr=pr->next;
}
ListNode* phead=pr->next;
pr->next=NULL;
end->next=head;
return phead;
}
};
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head==NULL||k<0) {
return head;
}
ListNode* end=head;
int len=1;
while(end->next) {
end=end->next;
len++;
}
if (k>=len) {
k=k%len;
}
if (k==0) {
return head;
}
ListNode* pos=head;
ListNode* pr=head;
while(pos&&k>0) {
k--;
pos=pos->next;
}
if (k>0) {
return head;
}
while(pos->next) {
pos=pos->next;
pr=pr->next;
}
ListNode* phead=pr->next;
pr->next=NULL;
end->next=head;
return phead;
}
};
相关文章推荐
- LeetCode:Rotate List(旋转链表)
- [LeetCode]61. Rotate List
- [leetcode]Rotate List
- LEETCODE: Rotate List
- LeetCode 61 - Rotate List
- LeetCode-61. Rotate List
- LeetCode Rotate List
- Leetcode 61. Rotate List
- LeetCode_61---Rotate List
- [leetcode-61]Rotate List(c)
- 【leetcode】Rotate List
- 061 Rotate List [Leetcode]
- leetcode Rotate list (链表旋转)的python实现
- leetcode - Rotate List
- 【Leetcode】【python】Rotate List
- LeetCode -- Rotate List
- [LeetCode]Rotate List
- LeetCode 61: Rotate List
- Leetcode 61. Rotate List
- C++ STL@ list 应用 (leetcode: Rotate Array)