Java 程式來旋轉列表的元素


在本文中,我們將瞭解如何旋轉列表的元素。List 擴充套件了 Collection 並宣告儲存一系列元素的集合的行為。Collection 是一種提供架構來儲存和操作物件組的框架。Java Collections 可以實現對資料執行的所有操作,如搜尋、排序、插入、操作和刪除。

以下是相同的示例 −

假設我們的輸入是

Input list: [100, 150, 200, 250, 300]

所需的輸出應該是

The list after one rotation: [150, 200, 250, 300, 100]

演算法

Step 1 - START
Step 2 - Declare a list namely input_list
Step 3 - Define the values.
Step 4 - Iterate through the list, and use the ‘get’ method to get the element at a specific index.
Step 5 - Assign this variable to a new variable ‘temp’.
Step 6 - Iterate through the list from the end, and fetch the element at a specific index. Use the ‘set’ method to set the value at ‘temp’.
Step 7 - Display the result
Step 8 - Stop

例子 1

在這裡,我們將 ‘main’ 函式下將所有操作繫結在一起。

import java.util.*;
public class Demo {
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<>();
      input_list.add(100);
      input_list.add(150);
      input_list.add(200);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + Arrays.toString(input_list.toArray()));
      for (int i = 0; i < 4; i++) {
         int temp = input_list.get(4);
         for (int j = 4; j > 0; j--) {
            input_list.set(j, input_list.get(j - 1));
         }
         input_list.set(0, temp);
      }
      System.out.println( "The list after one rotation: " + Arrays.toString(input_list.toArray()));
   }
}

輸出

The list is defined as: [100, 150, 200, 250, 300]
The list after one rotation: [150, 200, 250, 300, 100]

例子 2

在這裡,我們將操作封裝到函式中以展示面向物件的程式設計。

import java.util.*;
public class Demo {
   static void rotate(List<Integer> input_list){
      for (int i = 0; i < 4; i++) {
      int temp = input_list.get(4);
      for (int j = 4; j > 0; j--) {
         input_list.set(j, input_list.get(j - 1));
      }
      input_list.set(0, temp);
   }
   System.out.println("\nThe list after one rotation: " + Arrays.toString(input_list.toArray()));
   }
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<>();
      input_list.add(100);
      input_list.add(150);
      input_list.add(200);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + Arrays.toString(input_list.toArray()));
      rotate(input_list);
   }
}

輸出

The list is defined as: [100, 150, 200, 250, 300]

The list after one rotation: [150, 200, 250, 300, 100]

更新於: 30-Mar-2022

365 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.