028_自己实现一个LinkedList
生活随笔
收集整理的這篇文章主要介紹了
028_自己实现一个LinkedList
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/*** 自定義鏈表*/
public class MyLinkedList {private Node first;private Node last;private int size;/*** 構(gòu)造方法*/public MyLinkedList() {}/*** 鏈表大小* @return*/public int size() {return size;}/*** 數(shù)組是否為空* @return*/public boolean isEmpty() {return size == 0;}/*** 檢測下標(biāo)是否越界* @param index*/private void checkElementIndex(int index) {if(!(index >= 0 && index < size)) {throw new IndexOutOfBoundsException();}}/*** 插入元素位置是否合法* @param index* @return*/private void checkPositionIndex(int index) {if(!(index >= 0 && index <= size)) {throw new IndexOutOfBoundsException();}}/*** 往鏈表結(jié)尾插入元素* @param o*/private void linkLast(Object o) {Node temp = last;Node newNode = new Node(temp, o, null);last = newNode;if(temp == null) {first = newNode;}else {temp.next = newNode;}size++;}/*** 往某個(gè)節(jié)點(diǎn)之前插入元素* @param o* @param x*/private void linkBefore(Object o, Node x) {Node pre = x.prev;Node newNode = new Node(pre, o, x);x.prev = newNode;if(pre == null) {first = newNode;}else {pre.next = newNode;}size++;}/*** 添加元素* @param o* @return*/public boolean add(Object o) {linkLast(o);return true;}/*** * @param index* @param o* @return*/public void add(int index, Object o) {checkPositionIndex(index);if(index == size) {linkLast(o);}else {linkBefore(o, node(index));}}/*** 根據(jù)下標(biāo)獲取節(jié)點(diǎn)* @param index* @return*/private Node node(int index) {if(index < (size >> 1)) {Node x = first;for(int i = 0; i < index; i++) {x = x.next;}return x;}else {Node x = last;for(int i = size - 1; i > index; i--) {x = x.prev;}return x;}}/*** 根據(jù)下標(biāo)獲取元素* @param index* @return*/public Object get(int index) {checkElementIndex(index);return node(index).item;}/*** 刪除元素* @param x* @return*/private Object unlink(Node x) {Object element = x.item;Node next = x.next;Node prev = x.prev;if(prev == null) {first = next;}else {prev.next = next;x.prev = null;}if(next == null) {last = prev;}else {next.prev = prev;x.next = null;}x.item = null;size--;return element;}/*** 根據(jù)下標(biāo)刪除元素* @param index* @return*/public Object remove(int index) {checkElementIndex(index);return unlink(node(index));}/*** 根據(jù)元素刪除* @param o* @return*/public boolean remove(Object o) {if(o == null) {for(Node x = first; x != null; x = x.next) {if(x.item == null) {unlink(x);return true;}}}else {for(Node x = first; x != null; x = x.next) {if(o.equals(x.item)) {unlink(x);return true;}}}return false;}}class Node {Node prev;Object item;Node next;public Node() {}public Node(Node prev, Object item, Node next){this.prev = prev;this.item = item;this.next = next;}
}
?
總結(jié)
以上是生活随笔為你收集整理的028_自己实现一个LinkedList的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 027_自己实现一个ArrayList
- 下一篇: 029_自己实现一个HashMap