Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีกลับลำดับ Linked List ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธี กลับลำดับ (Reverse) Linked List ใน Android โดยใช้ Collections.sort() แล้วตามด้วย Collections.reverse() และใช้ LinkedHashSet เพื่อลบค่าซ้ำพร้อมรักษาลำดับ

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ในโค้ดข้างต้น ใช้ TextView เพื่อแสดง Linked List ที่กลับลำดับแล้ว

ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(2);
        linkedList.add(8);
        linkedList.add(2);
        linkedList.add(5);
        linkedList.add(7);
        linkedList.add(5);
        linkedList.add(9);

        // 1. จัดเรียงจากน้อยไปมาก
        Collections.sort(linkedList);
        // 2. กลับลำดับจากมากไปน้อย
        Collections.reverse(linkedList);
        // 3. ลบค่าซ้ำพร้อมรักษาลำดับ
        LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(linkedList);

        TextView textView = findViewById(R.id.text);
        textView.setText(hashSet.toString());
    }
}

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ

วิธีกลับลำดับ Linked List ใน Android

ข้อมูลต้นฉบับ: [2, 8, 2, 5, 7, 5, 9] → เรียง: [2, 2, 5, 5, 7, 8, 9] → กลับ: [9, 8, 7, 5, 5, 2, 2] → ลบซ้ำ: [9, 8, 7, 5, 2]