LinkedList是一種常見的資料結構,它的特性是在不連續的記憶體空間中保有連續性的資料
另外LinkedList也不需要特別定義串列長度,隨時可以做新增修改刪除
Java範例
LinkedList.java
package mypackage; public class LinkedList { private int val; private LinkedList next = null; private LinkedList prev = null; public LinkedList(LinkedList prev, LinkedList next) { this.next = next; this.prev = prev; } public int getVal() { return this.val; } public LinkedList getNext() { return this.next; } public LinkedList getPrev() { return this.prev; } public void setNext(LinkedList next) { this.next = next; } public void setPrev(LinkedList prev) { this.prev = prev; } public void setVal(int val) { this.val = val; } }
index.java
import mypackage.LinkedList; public class index { public static void main(String[] argv) { //建立LinkedList int [] arr = {3,4,5,6,1,2,7}; LinkedList tmp = null; //LinkedList第一筆node LinkedList first = null; for (int i = 0; i < arr.length; i++) { LinkedList link = new LinkedList(tmp,null); link.setVal(arr[i]); if (tmp != null) { //tmp為前一筆node tmp.setNext(link); } else { first = link; } tmp = link; } //插入node(插在第一筆之後) LinkedList second = first.getNext(); LinkedList new_node = new LinkedList(first,second); new_node.setVal(100); first.setNext(new_node); second.setPrev(new_node); //顯示LinkedList走訪 while (first != null) { System.out.println(first.getVal()); first = first.getNext(); } } }