题目要求将链表的末尾k%n个element移到最前。
先特殊判断链表中只有不多余2个element的情况。然后找到末尾的那个element并记录n,再找到新链表的末尾,断开;把旧链表的末尾接到开头。
代码:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *node1, *node2, *last;
int n = 0;
if(k == 0)
return head;
if(head == NULL)
return head;
last = head;
while(last->next) {
last = last->next;
n++;
}
n++;
k %= n;
if(k == 0)
return head;
node1 = head;
int j = n - k;
for(int i = 1 ; i < j ; i++) {
node1 = node1->next;
}
last->next = head;
head = node1->next;
node1->next = NULL;
return head;
}