LeetCode61- 旋轉鏈表

LeetCode61- 旋轉鏈表

最近全國疫情嚴重,待在家裏沒事幹,馬上又要準備春招了,最近刷刷題,記錄一下!再說一句,武漢加油,大家出門記得戴口罩!

1、題目

給定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動 k 個位置,其中 k 是非負數。
示例:

輸入: 1->2->3->4->5->NULL, k = 2
輸出: 4->5->1->2->3->NULL
解釋:
向右旋轉 1 步: 5->1->2->3->4->NULL
向右旋轉 2 步: 4->5->1->2->3->NULL

2、思路

在這裏插入圖片描述
在這裏插入圖片描述

3、代碼

c++

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return NULL;
        //計算鏈表長度
        int n=0;
        for(auto p=head;p;p=p->next)  n++//對k取模
        k%=n;
        auto first=head,second=head;
        //first指針先走K步
        while(k--)    first=first->next;
        //first、second指針同時前進,直到尾部爲止
        while(first->next)
        {
            first=first->next;
            second=second->next;
        }
        //first指針指向頭結點、secode的下個元素成爲頭結點,second指針指向null
        first->next=head;
        head=second->next;
        second->next=NULL;
        return head;     
    }
};

Java

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(!head) return null;
        for(ListNode p=head;p;p=p.next)  n++;
        k%=n;
        ListNode first=head,second=head;
        for(int i=1;i<=k;i++)
        {
            first=first.next;
        }
        
        while(first.next!=null)
        {
            first=first.next;
            second=second.next;
        }
        first.next=head;
        head=second.next;
        second.next=null;
        return head;   
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章