原题:
代码:
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
解决方法:
- 创建一个帮助节点,以便于返回。
- 先求出链表的长度,使k对链表长度求余,否则可能超时。
- 采用前后指针的方式,使前指针先往前走k步。
- 然后前后指针一起往前走,直到前指针的下一步就是链表结尾,这时后指针指向的是左半边最后一个节点。
- 将最后一个节点的下一个节点指向原来的头指针,将头指针指向右半部分的头结点,将左半部分的尾指针的下一个节点指向空。
代码:
int getLen(ListNode* head){
int len = 0;
while(head){
++len;
head = head->next;
}
return len;
}
ListNode* rotateRight(ListNode* head, int k) {
if (!head || !head->next)
return head;
int len = getLen(head);
k %= len;
ListNode dummy(INT_MIN);
dummy.next = head;
ListNode* cur = head, *fast = head;
for(int i = 0; i < k && fast; i++){
fast = fast->next;
}
if (!fast)
return head;
while(fast->next){
cur = cur->next;
fast = fast->next;
}
fast->next = dummy.next;
dummy.next = cur->next;
cur->next = NULL;
return dummy.next;
}