使用java實現單鏈表----(java中的引用就是指針)


//一直以為java中沒有指針,其實java的引用就是指針,只不過堆棧中的引用儲存了在堆中的地址,可以看做java中的指針。
public class sibgleLink<E> { // 結點內部類 private class Node { private Object data; private Node next = null; public Node() { data = null; } // 帶數據的構造函數 public Node(E data) { this.data = data; } } private Node head; // 頭引用(指針) private Node rear; // 尾引用(指針) private Node point; // 臨時引用(指針) private int length = 1; // 鏈表長度 // 帶參數的構造函數 public sibgleLink(E e) { head = new Node(); head.data = e; rear = head; length = 1; } // 尾插法 public void add(E elem) { point = new Node(elem); rear.next = point; rear = point; length++; } // 遍歷節點 public void traverse() { point = head; // 移動臨時引用到頭結點 if (head != null) System.out.print("[" + head.data + "]"); while (point.next != null) { System.out.print("->[" + point.next.data + "]"); point = point.next; } System.out.println(); } // 返回長度 public int length() { return this.length; } // 清除 public boolean clear() { while (head.next.next != null) { head.next = head.next.next; } head.next = null; rear = head; point = null; length = 1; return true; } // 插入元素 public boolean insert(int x, E data) { // 工作節點 point = head; int wz = 1; if (x == 1) { Node n = new Node(data); n.next = head; head = n; length++; return true; } if (x < 1 || x > this.length) { return false; } else { while (point.next != null && wz < x - 1) { point = point.next; wz++; } // 放入一個節點 Node n = new Node(data); n.next = point.next; point.next = n; length++; return true; } } // 刪除 public boolean del(int x) { point = head; int wz = 1; if (x < 0 || x > length) { return false; } else if (x == length) { point = head; while (point.next != null) { point = rear; point.next = null; length--; } } else { while (point.next != null && wz < x - 1) { point = point.next; wz++; } Node d = point.next; point.next = point.next.next; d = null; return true; } return false; } // 更改 public boolean change(int x, E data) { point = head; int wz = 1; if (x < 0 || x > length) { return false; } else { while (point.next != null && wz < x) { point = point.next; wz++; } point.data = data; return true; } } // 移動指針 private Node movePoint(int position) { if (position < 0) return head; if (position > length) return rear; if (position >= 0 && position <= length) { point = head; while (point != null) { if (position == 0) break; position--; point = point.next; } } return point; } public E find(int position) { if (position >= 0 && position < length) { Node tmp = movePoint(position); return (E) tmp.next.data; } return null; } // test public static void main(String[] args) { sibgleLink<Integer> si = new sibgleLink<Integer>(0); si.add(5); si.add(6); si.insert(2, 2); si.traverse(); si.del(3); si.traverse(); si.change(3, 77); si.traverse(); System.out.println(si.length()); } }

  結果:

[0]->[2]->[5]->[6]
[0]->[2]->[6]
[0]->[2]->[77]
4

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM