您的位置:首页 > 其它

leetcode - Rotate List

2013-11-25 22:07 253 查看
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (head == NULL ||  head->next ==NULL)
return head;
int size = 0;
ListNode * tmp = head;
while (tmp!=NULL){
size++;
tmp = tmp->next;
}
k = k%size;
if (k<=0)
return head;
ListNode * rhead = NULL, * ltail = NULL, * rtail = NULL;
ListNode * itr = head;
int i = 0;
while (itr !=NULL){
i++;
if (i==k){
ltail = NULL;
rhead = head;
}
else if (i>k){
ltail = rhead;
rhead = rhead->next;
}
rtail = itr;
itr = itr->next;
}
if (ltail!=NULL &<ail !=rtail)
ltail->next = NULL;
if (rhead!=NULL && rhead!=head){
rtail->next = head;
return rhead;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: