單鏈表資料結構,單鏈資料結構
鏈表中最簡單的一種是單向鏈表,每個元素包含兩個域,範圍和指標域,我們把這樣的元素稱之為節點。每個節點的指標域內有一個指標,指向下一個節點,而最後一個節點則指向一個空值。就是一個單向鏈表
一個單向鏈表的節點被分成兩個部分。第一個部分儲存或者顯示關於節點的資訊,第二個部分儲存下一個節點的地址。單向鏈表只可向一個方向遍曆。
使用java實現一個簡單的單鏈表,需要定義一個節點類、對節點的操作方法(add 、get、remove...)
** * 單鏈表資料結構簡單實現 * * @author jade * */public class SingleLinkedList<E> { private Node<E> head = null; // 每個鏈表都存有一個空值的頭結點。 private Node<E> tail = null; // 鏈表的最後一個結點,尾結點。 private int size = 0; // 當前鏈表中的節點數目。 /** * 建立一個空鏈表(建立其頭結點)。 */ public SingleLinkedList() { head = new Node<E>(); tail = head; } /** * 在鏈表的尾部插入資料 * @param e 待插入的資料 * * @return */ public boolean add(E e) { Node<E> node = new Node<E>(e); // 將要插入的值封裝成一個節點。 tail.setNext(node); // 將待插入結點放到尾結點的下一個結點。 tail = tail.getNext(); // 將新增加的結點設為尾節點。 ++size; // 鏈表大小增1。 return true; } /** * * @param index 待插入的位置 * @param e 待插入的元素 * * @return */ public boolean add(int index, E e) { checkValidateIndex(index); Node<E> newNode = new Node<E>(e); Node preNode = null; if (index > 0) { preNode = getNode(index - 1); }else{ preNode = head; } newNode.setNext(preNode.getNext()); preNode.setNext(newNode); return true; } /** * 擷取指定位置的結點的值 * @param index 欲擷取值的結點的下標 * * @return */ public E get(int index) { checkValidateIndex(index); Node<E> node = getNode(index); return node.getValue(); } /** * 刪除指定位置的結點 * @param index 待刪除結點的下標 * @return */ public boolean remove(int index) { Node<E> curNode = null; if (0 == index) { curNode = head.getNext(); Node<E> nextNode = curNode.getNext(); head.setNext(nextNode); } else { checkValidateIndex(index); curNode = getNode(index); // 擷取待刪除節點。 Node<E> preNode = getNode(index - 1); // 擷取待刪除節點的前一個結點。 preNode.setNext(curNode.getNext()); } curNode.setNext(null); // 將待刪除節點的下一結點置空。 return true; } /** * 設定指定位置結點的值。 * @param index 待設定值的結點的下標 * @param e */ public void set(int index, E e) { checkValidateIndex(index); Node<E> node = getNode(index); node.setValue(e); } /** * 擷取指定位置的結點 * @param index 擷取結點的下標 * */ private Node<E> getNode(int index) { checkValidateIndex(index); Node<E> node = head; for (int p = 0; p <= index; ++p) { node = node.getNext(); } return node; } /** * 驗證下標值是否合法,非法時拋出異常。 * @param index 待驗證的下標值 * @throws Exception * */ private void checkValidateIndex(int index) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException("無效的下標:" + index); } } /** * 擷取鏈表的大小。 * @return */ public int size() { return size; } /** * 鏈表中的節點,e代表節點的值,next是指向下一個節點的引用 * * @author jade * */ static class Node<E> { private E e; private Node<E> next = null; Node() { } Node(E e) { this.e = e; } public void setNext(Node<E> next) { this.next = next; } public Node<E> getNext() { return next; } public E getValue() { return e; } public void setValue(E e) { this.e = e; } }