在Java中實現鏈接列表
實現鍊錶的關鍵在於定義節點類並實現基本操作。 ①首先創建Node 類,包含數據和指向下一個節點的引用;②接著創建LinkedList 類,實現插入、刪除和打印功能;③append 方法用於在尾部添加節點;④printList 方法用於輸出鍊錶內容;⑤deleteWithValue 方法用於刪除指定值的節點,處理頭節點和中間節點的不同情況。
實現一個鍊錶在Java 中其實不難,關鍵是要理解鍊錶的結構和基本操作。下面我來一步步講清楚怎麼寫一個簡單的單向鍊錶。

什麼是鍊錶?
鍊錶是一種線性數據結構,它不像數組那樣連續存儲元素,而是通過“節點”把每個元素連接起來。每個節點包含兩個部分:一個是數據(比如一個整數),另一個是指向下一個節點的引用(指針)。
Java 中沒有內置的鍊錶結構,但我們可以自己定義類來實現。

定義節點類
首先我們要創建一個節點類Node
,這個類至少要包含兩個東西:
- 數據域,比如一個
int
值 - 指針域,指向下一個節點對象
class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } }
這裡我們初始化時默認next
是null
,表示當前節點後面沒有節點了。

實現鍊錶的基本操作
光有節點還不夠,還需要一個鍊錶類來管理這些節點。我們來實現幾個常用的操作:
插入節點
插入可以發生在頭部、尾部或者某個特定位置。我們先從最簡單的尾部插入開始。
class LinkedList { private Node head; // 在鍊錶末尾添加節點public void append(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; return; } Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } }
這段代碼的意思是:
- 如果頭節點為空,就讓新節點成為頭節點
- 否則遍歷整個鍊錶直到找到最後一個節點,然後把新節點接上去
打印鍊錶內容
為了驗證是否正確插入了節點,我們可以加一個打印方法:
public void printList() { Node current = head; while (current != null) { System.out.print(current.data " -> "); current = current.next; } System.out.println("null"); }
這樣就可以看到鍊錶中所有節點的數據了。
刪除指定值的節點
刪除操作稍微複雜一點,因為要考慮刪除的是不是頭節點,以及是否找到了目標值。
public void deleteWithValue(int data) { if (head == null) return; // 如果刪除的是頭節點if (head.data == data) { head = head.next; return; } Node current = head; while (current.next != null) { if (current.next.data == data) { current.next = current.next.next; // 跳過該節點return; } current = current.next; } }
這個方法只會刪除第一個匹配的節點。如果想刪掉所有匹配的節點,可以把return
改成繼續循環。
使用示例
你可以這樣使用上面定義的鍊錶類:
public class Main { public static void main(String[] args) { LinkedList list = new LinkedList(); list.append(10); list.append(20); list.append(30); list.printList(); // 輸出: 10 -> 20 -> 30 -> null list.deleteWithValue(20); list.printList(); // 輸出: 10 -> 30 -> null } }
基本上就這些。只要搞清楚節點是怎麼連在一起的,再配合一些基礎操作,就能實現一個可用的鍊錶了。像插入到指定位置、查找、反轉等操作也可以在這個基礎上繼續擴展。
以上是在Java中實現鏈接列表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

容器化Java應用:創建Dockerfile,使用基礎鏡像如eclipse-temurin:17-jre-alpine,複製JAR文件並定義啟動命令,通過dockerbuild構建鏡像並用dockerrun測試本地運行。 2.推送鏡像到容器註冊表:使用dockertag標記鏡像並推送到DockerHub等註冊表,需先登錄dockerlogin。 3.部署到Kubernetes:編寫deployment.yaml定義Deployment,設置副本數、容器鏡像和資源限制,編寫service.yaml創建

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

JavaserializationConvertSanObject'SstateIntoAbyTeSteAmForStorageorTransermission,andDeserializationReconstructstheObjectStheObjectFromThstream.1.toenableserialization,aclassMustimustimplementTheSerializableizableface.2.UseObjectObjectObjectObjectOutputputputputputtreamToserialializeanobectizeanobectementeabectenobexpent,savin

ahashmapinjavaiSadattrastureturethatStoreskey-valuepairsforefficeFitedReval,插入和deletion.itusesthekey’shashcode()methodtodeTermInestorageLageLageAgeLageAgeAgeAgeAgeAneStorageAgeAndAllowSavereo(1)timecomplexityforget()

toCreateAnduseanArrayInjava,第一declethearraywithththetatepeandsquarebarackets,thanStantiateItWithTheneWkeyWordeRinitialIseIsizitDirectlywithvalues; 1.DecleAteAteAndeAnArrayUsishArayusisherusingDataType [] ArraynAmeDatepe [] arraynAmename = newDatatepe [size]

YouCancReateathReadInjavaByExtDingTheThEthEthEthReadClassOrimplementingTherunnablefface.2.ExtDendingThreadThreadInvolvesCreatingingAclassThatoverRidestherun()MethodAndCallingStart()onaninstance.3.implementingrementingRunnnablerequirequirequirequirequiresdefinterun()
