日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

028_自己实现一个LinkedList

發布時間:2025/4/17 编程问答 68 豆豆
生活随笔 收集整理的這篇文章主要介紹了 028_自己实现一个LinkedList 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*** 自定義鏈表*/ public class MyLinkedList {private Node first;private Node last;private int size;/*** 構造方法*/public MyLinkedList() {}/*** 鏈表大小* @return*/public int size() {return size;}/*** 數組是否為空* @return*/public boolean isEmpty() {return size == 0;}/*** 檢測下標是否越界* @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();}}/*** 往鏈表結尾插入元素* @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++;}/*** 往某個節點之前插入元素* @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));}}/*** 根據下標獲取節點* @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;}}/*** 根據下標獲取元素* @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;}/*** 根據下標刪除元素* @param index* @return*/public Object remove(int index) {checkElementIndex(index);return unlink(node(index));}/*** 根據元素刪除* @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;} }

?

總結

以上是生活随笔為你收集整理的028_自己实现一个LinkedList的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。