[LeetCode] 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.

解法:遊標指針從頭節點向後移動,當指向尾節點時,得到鏈表長度len,同時將鏈表頭尾相連,接着遊標再向後移動 len - k%len 步得到結果鏈表的尾節點。

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head)
        {
            ListNode *p = head;
            int len =1;
            while(p -> next)
            {
                p = p -> next;
                len++;
            }
            p -> next = head;
            k %= len;
            int move = len - k;
            while (move > 0)
            {
                p = p -> next;
                move--;
            }
            head = p -> next;
            p -> next = NULL;
        }
        return head;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章