Leetcode ☞ 61. Rotate List

61. Rotate List

My Submissions
Question
Total Accepted: 63354  Total Submissions: 279889  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.











我的AC:(4ms,最快一批)

struct ListNode* rotateRight(struct ListNode* head, int k) {
    if (!head || !head->next)   return head;
    
    struct ListNode *count, *newHead, *newTail, *tail;
    count = newHead = head;
    int len = 0, realK;
    
    while(count){
        count = count->next;
        len++;
    }
    count = head;
    
    realK = k % len;//【1,2】 k=3;  【1,2,3】k=2000000
    if (realK == 0)
        return head;
    
    while(realK--){
        count = count->next;
    }
    while(count){
        tail = count;
        count = count->next;
        newTail = newHead;
        newHead = newHead->next;
    }//循环后count为NULL,tail为最后一个节点,newHead在不算NULL的倒数第K个节点,newTail是new的前一个节点,即return时链表的最后一个节点。
    newTail->next = NULL;
    tail->next = head;
    
    return newHead;
}

提交一次后才想到 k比数组长度多很多的这种情况!所以要求k%len。


思路:

跟Leetcode ☞ 19. Remove Nth Node From End of List ☆ 一样的思想/目的,即:找到倒数第K个点。





你可能感兴趣的:(Leetcode ☞ 61. Rotate List)