Rotate List
Difficulty:Medium
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
.
题目就是把链表循环右移k个位置,我是先把首尾相连,然后根据k进行移位找到新的末尾和开头
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL)
return NULL;
int size = 1;//节点数
ListNode *last = head ,*p = head,*newHead = NULL;
while (last->next != NULL){//找到末尾和节点数
last = last->next;
size++;
}
last->next = head;//头尾连接
k = k%size;//取余
int nextLast = abs(size - k - 1);//移位数
while (nextLast > 0){//右移位找到新的尾部
p = p->next;
nextLast--;
}
newHead = p->next;//新的头
p->next = NULL;//新的尾
return newHead;
}