Node.javajava
package com.wanali.java_ds.linklist; //節點類 public class Node { public Object data; public Node next; // 無參的構造函數 public Node() { this.data = null; this.next = null; } // 一個參數的構造函數 public Node(Object data) { this.data = data; this.next = null; } // 兩個參數的構造函數 public Node(Object data, Node next) { this.data = data; this.next = next; } }
LinkList.javanode
package com.wanali.java_ds.linklist; //鏈表類 public class LinkList { public Node head; public LinkList next; // 初始化頭結點 public LinkList() { head = new Node(); } public void creat(int i, Object x) { Node p = new Node(x);// 實例化一個節點 Node pNode = head; while (pNode != null) pNode = pNode.next; pNode.next = p; } public void display() { Node pNode = head.next; while (pNode != null) { System.out.println(pNode.data); pNode = pNode.next; } } // 插入 public void insert(int i, Object x) throws Exception { Node pNode = head; int j = 0;// while (pNode != null && j < i - 1) { pNode = pNode.next; ++j; } if (j > i - 1 || pNode == null) throw new Exception("插入的位置不合法"); Node t = new Node(x); t.next = pNode.next; pNode.next = t; } public void delete(int i) { Node pNode = head; if (i < 1) System.out.println("輸入的值不正確!!!"); while (pNode.next != null && --i > 0) { pNode = pNode.next; } Node delnode = pNode.next; pNode.next = delnode.next; } public Object get(int i) { Node pNode = head; int j = 0; while (pNode != null && j != i) { pNode = pNode.next; j++; } return pNode.data; } public Object length() { Node pNode = head; int j = 0; while (pNode != null) { pNode = pNode.next; j++; } return j; } }
TestLinkList.java函數
package com.wanali.java_ds.linklist; public class TestLinkList { public static void main(String[] args) { LinkList linkList = new LinkList(); try { linkList.creat(1, 10); linkList.creat(2, 20); linkList.creat(3, 30); System.out.println("打印鏈表中的元素:"); linkList.display(); System.out.println("在第2個位置插入元素:"); linkList.insert(2, 0); linkList.display(); System.out.println("插入的元素爲:" + linkList.get(2)); System.out.println("刪除第3個元素:"); linkList.delete(3); linkList.display(); System.out.println("鏈表長度爲:" + "\n" + linkList.length()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
運行結果以下:this