[leetcode]Rotate List

来源:互联网 发布:淘宝购买失败系统异常 编辑:程序博客网 时间:2024/04/30 01:33

Rotate List

 

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

   ListNode *rotateRight(ListNode *head, int k) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(head == NULL) return NULL;        ListNode *tail;        ListNode *ptr = head;        int n = 0;        //统计链表元素个数,并记录最后一个元素        while(ptr){            if(ptr->next == NULL) tail = ptr;            ptr = ptr->next;            n++;        }        k %= n;//如果k是链表元素的整数倍则不移动,只可移动n个元素之内的k        if(k == 0) return head;        ListNode *piovt = head;        ptr = head;        while(k--){            ptr = ptr->next;//先移动k个元素,为找出倒数第k个元素做准备        }        ptr = ptr->next;//找出倒数第k+1个元素        while(ptr && piovt){            piovt = piovt->next;            ptr = ptr->next;        }        ListNode *nhead = piovt->next;//新的表头        piovt->next = NULL;//新的表尾指向空        tail->next = head;//将两段链表连接起来        return nhead;    }

.

0 0
原创粉丝点击