Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java xoay vòng (rotate) phần tử List


Trong bài viết này, chúng ta sẽ hiểu cách xoay vòng phần tử của List. List kế thừa Collection và khai báo hành vi của collection lưu trữ chuỗi phần tử. Collection là framework cung cấp kiến trúc lưu trữ và thao tác nhóm đối tượng. Java Collections có thể thực hiện mọi thao tác trên dữ liệu: tìm kiếm, sắp xếp, chèn, thao tác, xóa.

Minh họa dưới đây:

Giả sử đầu vào là:

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

Đầu ra mong muốn:

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

Thuật toán

Bước 1 - BẮT ĐẦU 
Bước 2 - Khai báo list input_list 
Bước 3 - Định nghĩa giá trị 
Bước 4 - Duyệt list, dùng 'get' lấy phần tử tại chỉ số cụ thể 
Bước 5 - Gán biến này cho biến tạm 'temp' 
Bước 6 - Duyệt list từ cuối, lấy phần tử tại chỉ số cụ thể. Dùng 'set' gán giá trị tại 'temp' 
Bước 7 - Hiển thị kết quả 
Bước 8 - DỪNG

Ví dụ 1

Gom thao tác dưới 'main'.

import java.util.*; 

public class Demo { 
    public static void main(String[] args){ 
        List 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())); 
    } 
}

Kết quả

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

Ví dụ 2

Đóng gói thao tác vào hàm thể hiện lập trình hướng đối tượng.

import java.util.*; 

public class Demo { 
    static void rotate(List 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 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); 
    } 
}

Kết quả

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