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个,需要把新头前面的node指向null,把链表尾巴指向旧头。要处理k大于表长度的情况。
- ListNode *rotateRight(ListNode *head, int k) {
- if(!head) return NULL;
- if(k == 0) return head;
- ListNode *tail = head, *prev = head;
- int i = k;
- //find last k+1-th elem and last elem.
- while(k>0 &&tail->next != NULL){
- tail = tail->next;
- k--;
- }
- //list length is i-k+1
- if(tail->next == NULL) {
- int listlen = i - k + 1;
- k =listlen - i%listlen-1;
- while(k>0){prev = prev->next; k--;}
- }
- while(tail->next != NULL){
- prev = prev->next;
- tail = tail->next;
- }
- tail->next = head;
- head = prev->next;
- prev->next = NULL;
- return head;
- }
No comments:
Post a Comment