/*** 節點類* @author JP* */
class Node {Object value;//節點元素值Node pre;//上一個節點Node next;//下一個節點public Node(Object value) {this.value = value;}
}/*** 鏈表類* @author JP**/
public class MyLinkedList {Node cur;//目前指向的節點Node head;//頭結點Node end;//尾節點int size = 0;/*** 實例化頭節點和尾節點*/public MyLinkedList() {head = new Node("head");end = new Node("end");//設置頭尾相連head.next = end;end.pre = head;}/*** 增加操作* @param value*/public void add(Object value) {//判斷當前插入的元素是否是第一個元素if (cur == null) {cur = new Node(value);head.next = cur;cur.pre = head;} else {Node node = new Node(value);cur.next = node;node.pre = cur;cur = node;//將cur元素設置為當前插入的節點}cur.next = end;end.pre = cur;size++;}/*** 在指定位置插入元素,第一個元素的下標為0* @param index* @param value* @throws Exception*/public void add(int index, Object value) throws Exception {//判斷當前要插入的元素是否為鏈表的最后一個元素if (index == size) {this.add(value);} else {Node tmp = this.get(index);//當前index位置所對應的節點Node node = new Node(value);//當前要插入的節點tmp.pre.next = node;node.pre = tmp.pre;node.next = tmp;tmp.pre = node;}size++;}/*** 刪除指定位置的元素,第一個元素的下標為0* @param index* @throws Exception */public void remove(int index) throws Exception {Node tmp = this.get(index);//當前index位置所對應的節點tmp.pre.next = tmp.next;tmp.next.pre = tmp.pre;size--;}/*** 獲取指定位置的節點元素* @param index* @return* @throws Exception */public Node get(int index) throws Exception {if (index < 0 || index >= size) {throw new Exception("數組下標越界!");}Node node = head.next;for (int i = 1; i <= index; i++) {node = node.next;//迭代為下一個節點}return node;}/*** 將鏈表轉化成數組* @return*/public Object[] toArray() {Object[] arr = new Object[size];Node node = head.next;for (int i = 0; i < arr.length; i++) {arr[i] = node.value;node = node.next;//迭代為下一個節點}return arr;}public static void main(String[] args) throws Exception {MyLinkedList list = new MyLinkedList();list.add(1);list.add(2);list.add(3);list.add(4);//list.remove(4);//list.add(4,"a");Object[] arr = list.toArray();for (Object obj : arr) {System.out.println(obj);}}
}