การหมุนองค์ประกอบใน List (Rotate)
การหมุน (Rotate) คือการเลื่อนองค์ประกอบในลิสต์ไปทางซ้ายหรือขวา โดยองค์ประกอบที่หลุดออกมาจะกลับเข้ามาอีกด้านหนึ่ง Java มี Collections.rotate() สำเร็จรูป แต่ตัวอย่างนี้แสดงการทำงานภายใน (Manual Rotation)
อัลกอริทึมหมุนซ้าย 1 ตำแหน่ง (Manual)
- เก็บองค์ประกอบสุดท้ายไว้ในตัวแปร temp
- เลื่อนองค์ประกอบทุกตัวไปทางซ้าย (index ลดลง)
- วางค่า temp ไว้ที่ index 0
ตัวอย่างที่ 1: Manual Rotation ใน main
import java.util.*;
public class Demo {
public static void main(String[] args) {
List inputList = new ArrayList<>();
inputList.add(100);
inputList.add(150);
inputList.add(200);
inputList.add(250);
inputList.add(300);
System.out.println("ลิสต์เดิม: " + inputList);
// หมุนซ้าย 1 ตำแหน่ง (Manual)
int temp = inputList.get(inputList.size() - 1); // เก็บตัวสุดท้าย
for (int j = inputList.size() - 1; j > 0; j--) {
inputList.set(j, inputList.get(j - 1)); // เลื่อนซ้าย
}
inputList.set(0, temp); // วางตัวสุดท้ายไว้หน้าสุด
System.out.println("หลังหมุนซ้าย 1 ครั้ง: " + inputList);
}
}
ผลลัพธ์
ลิสต์เดิม: [100, 150, 200, 250, 300]
หลังหมุนซ้าย 1 ครั้ง: [300, 100, 150, 200, 250]
ตัวอย่างที่ 2: ใช้ Collections.rotate() (แนะนำ)
import java.util.*;
public class Demo {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList(100, 150, 200, 250, 300));
System.out.println("ก่อนหมุน: " + list);
// หมุนขวา 2 ตำแหน่ง (positive = right, negative = left)
Collections.rotate(list, 2);
System.out.println("หมุนขวา 2: " + list);
// หมุนซ้าย 1 ตำแหน่ง
Collections.rotate(list, -1);
System.out.println("หมุนซ้าย 1: " + list);
}
}
ผลลัพธ์ Collections.rotate()
ก่อนหมุน: [100, 150, 200, 250, 300]
หมุนขวา 2: [250, 300, 100, 150, 200]
หมุนซ้าย 1: [300, 100, 150, 200, 250]
ตัวอย่างที่ 3: Encapsulation แบบ OOP
import java.util.*;
public class Demo {
static void rotateLeft(List list, int positions) {
if (list == null || list.isEmpty()) return;
positions = positions % list.size();
if (positions < 0) positions += list.size();
Collections.rotate(list, -positions);
}
static void rotateRight(List list, int positions) {
if (list == null || list.isEmpty()) return;
Collections.rotate(list, positions);
}
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList(100, 150, 200, 250, 300));
System.out.println("ต้นฉบับ: " + list);
rotateLeft(list, 1);
System.out.println("หมุนซ้าย 1: " + list);
rotateRight(list, 2);
System.out.println("หมุนขวา 2: " + list);
}
}
ประสิทธิภาพ
Collections.rotate(): O(n) - ใช้การสลับบล็อก (block swap) มีประสิทธิภาพดี- Manual loop: O(n) แต่มี overhead สูงกว่า
- สำหรับ LinkedList: rotate() ยังคง O(n) แต่ช้ากว่า ArrayList เนื่องจากไม่มี random access
กรณีการใช้งาน
- Circular buffer / Ring buffer
- Game development (sprite animation)
- Load balancing (Round robin)
- Cryptography algorithms