鏈表的旋轉

題目:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.


解題思路:

觀察發現,如果我們將元素收尾相連,然後將頭結點的指針向右移動k個位置,再將鏈表斷開就得到了我們想要的結果。


代碼實現:

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head == NULL)
            return NULL;
        if(k < 0)
            return head;
        //count爲鏈表中結點個數
        int count = 1;
        ListNode* cur = head;
        while(cur->next != NULL)
        {
            count++;
            cur = cur->next;
        }
        k %= count;
        //現將鏈表連成一個環,然後將head向後走count-k步,將環斷開
        cur->next = head;
        int step = count - k;
        ListNode* pre = head;
        while(step--)
        {
            pre = head;
            head = head->next;
        }
        pre->next = NULL;
        return head;
    }
};

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