雙鏈表java實現

來源:互聯網
上載者:User

主要注意結構體的建立和雙鏈表添加刪除操作中結構圖應用的改變。具體改變細節請看代碼注釋,代碼不當之處希望各位加以提點,謝謝

/** *  * <p> * 功能描述:迴圈雙鏈表 * </p> *  * @author 鐘良健 * @company * @version V1.0 */public class util<T> {private Node<T> head;private int size;@SuppressWarnings("hiding")public class Node<T> {private Node<T> next;private Node<T> privious;private T value;public Node(Node<T> privious, Node<T> next, T value) {this.privious = privious;this.next = next;this.value = value;}}public util() {head = new Node<T>(null, null, null);head.privious = head.next = head;size = 0;}/** *  * 方法描述: 1、首先判斷指定位置的節點是鏈表的前半段還是後半段 2、若為前半段則通過前端節點的順序尋找 3、若為後半段則通過前端節點的逆向尋找 * 注意:1、預設前端節點位置為0 2、注意for迴圈大小 *  * @param index * @return 指定位置的節點 * @author 鐘良健 */public Node<T> getNodeByIndex(int index) {if (index == 0) {System.out.println(head);return head;}if (index < 0 || index > size) {throw new IndexOutOfBoundsException("超出尋找範圍");}Node<T> node = null;if (index < size / 2) {for (int i = 0; i < index; i++) {node = head.next;}System.out.println(node);return node;}for (int j = 0; j < size - index + 1; j++) {node = head.privious;}System.out.println(node);return node;}/** *  * 方法描述: 插入節點到指定位置節點處 1、首先根據插入節點的位置尋找出原本位置的節點 * 2、new出一個新節點,新節點的前驅節點為原本位置節點的前驅節點,新節點的後驅節點為原本位置節點 * 3、原本位置節點的前驅節點的後驅節點指向新節點,原本位置的節點的前驅節點為新節點 *  * @param index *            指定位置 * @param t *            節點值 * @author 鐘良健 */public void insertNodeByIndex(int index, T t) {Node<T> oldPositionNode = getNodeByIndex(index);Node<T> newPositionNode = new Node<T>(oldPositionNode.privious,oldPositionNode, t);oldPositionNode.privious.next = newPositionNode;oldPositionNode.privious = newPositionNode;size++;}/** *  * 方法描述: *  * @param index * @author 鐘良健 */public void deleteNodeByIndex(int index) {Node<T> deleteNode = getNodeByIndex(index);deleteNode.privious.next = deleteNode.next;deleteNode.next.privious = deleteNode.privious;deleteNode = null;size--;}public void displaylist() {Node<T> node = head;for (int i = 0; i < size; i++) {node = node.next;System.out.println(node.value);}}public static void main(String[] args) {util<String> list = new util<String>();list.insertNodeByIndex(0, "1");list.insertNodeByIndex(0, "2");list.insertNodeByIndex(0, "3");list.insertNodeByIndex(0, "4");list.displaylist();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.