[leetcode]Rotate List

来源:互联网 发布:java spring压缩 编辑:程序博客网 时间:2024/06/06 16:32

Rotate List

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.

题目就是把链表循环右移k个位置,我是先把首尾相连,然后根据k进行移位找到新的末尾和开头

   ListNode* rotateRight(ListNode* head, int k) {        if (head == NULL)return NULL;int size = 1;//节点数ListNode *last = head ,*p = head,*newHead = NULL;while (last->next != NULL){//找到末尾和节点数last = last->next;size++;}last->next = head;//头尾连接k = k%size;//取余int nextLast = abs(size - k - 1);//移位数while (nextLast > 0){//右移位找到新的尾部p = p->next;nextLast--;}newHead = p->next;//新的头p->next = NULL;//新的尾return newHead;    }


0 0