29_leetcode_Rotate List

来源:互联网 发布:耻辱2盗版优化补丁 编辑:程序博客网 时间:2024/06/18 18:38

     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.

1:链表NULL或者k<= 0;  2:统计链表节点个数并k % n; 3:设置两个指针,其中一个指针先走k个节点;4:两个指针同时走,5:注意交换指针

 ListNode *rotateRight(ListNode *head, int k) {                if(head == NULL || k <= 0)            return head;                int count = 0;        ListNode* index = head;        while(index != NULL)        {            count++;            index = index->next;        }                k = k % count;        if( k == 0)            return head;                ListNode* fast = head;        ListNode* slow = head;                for(int i = 0; i < k; i++)        {            fast = fast->next;        }                while(fast->next)        {            slow = slow->next;            fast = fast->next;        }                ListNode* tempHead = slow->next;        slow->next = NULL;        fast->next = head;        head = tempHead;                return head;    }


0 0