如何在 Android 中反轉一個連結串列?
本示例演示如何在 Android 中反轉連結串列。
步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟 2 − 向 res/layout/activity_main.xml 新增以下程式碼。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://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>
在上面的程式碼中,我們採用了一個文字檢視來顯示連結串列的反轉。
步驟 3 − 向 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.HashSet; 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); Collections.sort(linkedList); Collections.reverse(linkedList); LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(linkedList); TextView textView = findViewById(R.id.text); textView.setText(hashSet.toString()); } }
讓我們嘗試執行應用程式。我假設你已將實際的 Android 移動裝置連線到計算機。要從 Android Studio 執行應用程式,請開啟一個專案活動檔案,然後從工具欄中單擊執行 圖示。選擇你的移動裝置作為選項,然後檢查移動裝置,它將顯示你的預設螢幕 −
單擊 此處 下載專案程式碼
廣告