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

วิธีหาค่ากลางใน Linked List บน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีหา ค่ากลาง (middle element) ใน LinkedList บน Android โดยการหารขนาดของลิสต์ด้วย 2

ขั้นตอนที่ 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.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> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

        // หาตำแหน่งกลาง: size / 2
        int middleIndex = list.size() / 2;

        TextView textView = findViewById(R.id.text);
        textView.setText(String.valueOf(list.get(middleIndex)));
    }
}

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

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

วิธีหาค่ากลางใน Linked List บน Android

Linked List มี 7 สมาชิก (1-7) ตำแหน่งกลางคือ index 3 (7/2 = 3) ค่าที่ได้คือ 4