LeetCode //C - 61. リストの回転

61. リストの回転

リンクされたリストの先頭を指定して、リストを右にk桁回転します。
 

例 1:

ここに画像の説明を挿入

入力: head = [1,2,3,4,5]、k = 2
出力: [4,5,1,2,3]

例 2:

ここに画像の説明を挿入

入力: head = [0,1,2]、k = 4
出力: [2,0,1]

制約:

  • リスト内のノード数の範囲は [0, 500] です。
  • -100 <= Node.val <= 100
  • 0 < = k < = 2 ∗ 1 0 9 0 <= k <= 2 * 10^90<=k<=21 09

From: LeetCode
Link: 61. リストの回転


解決:

アイデア:
  1. 長さを見つける:まず、リストを走査してその長さnを見つけます。
  2. 有効回転の計算:長さ n 桁のリストを回転することは、まったく回転しないことと同じであるため、k mod n桁を回転するだけで済みます。
  3. 新しいヘッドの検索:リストを ( n−k mod n ) 番目のノードまでたどります。これが回転後の新しい尾部になります。
  4. 回転の実行:新しい末尾の次のポインタをNULLに更新し、古い末尾の次のポインタを古い先頭に設定します。
コード:
struct ListNode* rotateRight(struct ListNode* head, int k) {
    
    
    if (head == NULL || k == 0) {
    
    
        return head;
    }
    
    // Step 1: Find the length of the list
    int n = 1;
    struct ListNode *tail = head;
    while (tail->next != NULL) {
    
    
        n++;
        tail = tail->next;
    }
    
    // Step 2: Calculate the effective number of rotations needed
    k = k % n;
    if (k == 0) {
    
    
        return head;
    }
    
    // Step 3: Find the new head and tail
    struct ListNode *new_tail = head;
    for (int i = 0; i < n - k - 1; i++) {
    
    
        new_tail = new_tail->next;
    }
    struct ListNode *new_head = new_tail->next;
    
    // Step 4: Perform the rotation
    new_tail->next = NULL;
    tail->next = head;
    
    return new_head;
}

おすすめ

転載: blog.csdn.net/navicheung/article/details/132594806