Rotate List
找出新list的尾部所在的位置就好办了,不过要注意右移的位置比list本身要长的情形,需要求余。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *rotateRight(ListNode *head, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!head) return NULL; int len = 0; ListNode* pos = head; ListNode* tail = head; while (pos) { ++len; tail = pos; pos = pos->next; } int actual_k = (len - k%len)%len; if (0 == actual_k) return head; ListNode* pre = head; pos = head; while (actual_k-- > 0) { pre = pos; pos = pos->next; } pre->next=NULL; tail->next = head; return pos; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号