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;
    }
};

 

posted @ 2013-06-16 13:41  dmthinker  阅读(82)  评论(0)    收藏  举报