標籤:java鏈表 鏈表 list
public class MyList { static class Node {// 節點類 Object data; Node next; public Node(Object data) {// 構造方法,為data賦值 this.data = data; this.next = null; } } Node head; public MyList() { head = null;// 鏈表的構造方法 } public void clear() {// 清除鏈表 head = null; } public void bianli()// 遍曆 { Node p = head; while (p != null) { System.out.print(p.data + " "); p = p.next; } System.out.println(); } public boolean isEmpty()// 判斷是否為空白 { return head == null; } public int size() {// 節點個數 Node p = head; int sum = 0; while (p != null) { sum++; p = p.next; } return sum; } // 在指定位置插入元素,下標從0開始 public void insert(Object d, int pos) { if (pos < 0 || pos > size()) { throw new RuntimeException("下標錯誤"); } Node newNode = new Node(d); if (pos == 0) { newNode.next = head; head = newNode; } else if (pos >= size() - 1) { get(size() - 1).next = newNode; } else { newNode.next = get(pos); get(pos - 1).next = newNode; } } public Node get(int pos) { if (pos < 0 || pos > size()) { throw new RuntimeException("下標錯誤"); } if (pos == 0) return head; Node p = head; for (int i = 0; i < pos; i++) p = p.next; return p; } public static void main(String[] args) { MyList list = new MyList(); list.insert(10, 0); list.insert(20, 1); list.insert(30, 0); list.insert(40, 1); System.out.println(list.size()); list.bianli(); System.out.println(list.isEmpty()); System.out.println(list.get(2).data); list.clear(); System.out.println(list.isEmpty()); }}
Java 實現一個鏈表