leetcode第一刷_Rotate List

來源:互聯網
上載者:User

我提交了好多次,錯誤莫名其妙的,到後來才明白過來,原來我把題目給理解錯了。

這個題的意思不是說讓你把最後的那k個位置的元素移到前面來,這種問題的做法就是用兩個指標,先讓一個走,走到一定的長度之後兩個一起走,很簡單。它實際的意思是整個鏈表迴圈右移,假設一個鏈表長度是N,那麼迴圈右移N次之後,鏈表又變回了原來的樣子。k的取值範圍只說了是非負的,也就是它可以是大於N的,因此實際的移位次數只是(k%N)而已。

代碼就不多說了,很簡單。

class Solution {public:    ListNode *rotateRight(ListNode *head, int k) {        if(!head||!head->next||k==0)            return head;        int i=0, len=0;        ListNode *pre=head, *pNode = head, *newHead;        while(pNode){            len++;            pNode = pNode->next;        }        pNode = head;        k %= len;        if(k == 0)  return head;        while(i<k&&pNode){            pNode = pNode->next;            i++;        }        while(pNode->next){            pre = pre->next;            pNode = pNode->next;        }        newHead = pre->next;        pre->next = NULL;        pNode->next = head;        return newHead;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.