單鏈表java簡易實現

來源:互聯網
上載者:User

標籤:==   有一個   ++   link   構建   --   ringbuf   dex   highlight   

鞏固資料結構 單鏈表java實現 單鏈表除了表尾 每個幾點都有一個後繼 結點有資料和後繼指標組成  通過構建表頭和表尾(尾部追加需要)兩個特殊幾點 實現單鏈表的一些操作,代碼如下

package com.shine.test.datastruct;/** * 簡易鏈表 *  * @author SHINE * * @param <E> */public class LinkList<E> {private Node head, tail;private int size = 0;protected class Node<E> {E data;Node next;}public LinkList() {head = new Node();head.next = null;tail = new Node<E>();}public void insert(E e, int index) {Node newNode = new Node<E>();newNode.data = e;Node before = head;Node temp = head.next;while (index >= 0) {if (index == 0) {before.next = newNode;newNode.next = temp;size++;break;}before = temp;temp = temp.next;index--;}}public void add(E e) {Node node = new Node();node.data = e;node.next = null;if (head.next == null) {head.next = node;}tail.next = node;tail = node;size++;}public E get(int index) {if (index > size - 1) {return null;}Node temp = head.next;while (index >= 0) {if (index == 0) {return (E) temp.data;}temp = temp.next;index--;}return null;}public E getFirst() {return get(0);}public E getLast() {return get(size - 1);}public void remove(E e) {Node before = head;Node temp = head.next;while (temp != null) {if (temp.data.equals(e)) {before.next = temp.next;size--;break;}before = temp;temp = temp.next;}}@Overridepublic String toString() {StringBuffer sb = new StringBuffer();Node temp = head.next;while (temp != null) {sb.append(temp.data + "->");temp = temp.next;}return sb.toString();}public int getLength() {return size;}}

  

單鏈表java簡易實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.