手寫LinkedList, 增加小分裝,增加泛型約束
阿新 • • 發佈:2018-12-13
package com.jianshun; public class Node { Node previous; //上一個節點 Node next; //下一個節點 Object element; //元素資料 public Node(Node previous, Node next, Object element) { super(); this.previous = previous; this.next = next; this.element = element; } public Node(Object element) { super(); this.element = element; } }
package com.jianshun; /** * 自定義一個連結串列 * 增加小的封裝,增加泛型 * @author Administrator * */ public class SxtLinkedList05<E> { private Node first; private Node last; private int size; public void add(int index,E element){ checkRange(index); Node newNode = new Node(element); Node temp = getNode(index); if(temp!=null){ Node up = temp.previous; if(up == null){//把元素插入到位首 first = newNode; newNode.next = temp; temp.previous = newNode; }else if(size == index){//將元素插入到末尾 //待續 }else{ up.next = newNode; newNode.previous = up; newNode.next = temp; temp.previous = newNode; } } size++; } //[] //['a','b','c'] public void add(E element){ Node node = new Node(element); if(first == null){ node.previous = null; node.next = null; first = node; last = node; }else{ node.previous = last; node.next = null; last.next = node; last = node; } size++; } //根據下標刪除資料 public void remove(int index){ checkRange(index); Node temp = getNode(index); if(temp != null){ Node up = temp.previous; Node down = temp.next; //被刪除的元素是第一個時 if(index == 0){ first = down; } //被刪除的元素是最後一個時候 if(index == size-1){ last = up; } if(up!=null){ up.next = down; } if(down!=null){ down.previous = up; } size--; } } //根據下標獲取節點(程式碼重用) private Node getNode(int index){ checkRange(index); Node temp = null; if(index <= (size>>1)){ //size >>1 相當於除以2 temp = first; for(int i=0; i<index; i++){ temp = temp.next; } }else{ temp = last; for(int i=size-1; i>index; i--){ temp = temp.previous; } } return temp; } //[] //[a,b,c,d,e,f] c-2 public E get(int index){ checkRange(index); Node temp = getNode(index); return (E) (temp !=null ? temp.element : null); } //分裝對索引的呼叫 public void checkRange(int index){ if(index <0 || index >size - 1){ throw new RuntimeException("索引數字不合法:"+index); } } @Override public String toString() { //[a,b,c] first=a, last=c StringBuilder sb = new StringBuilder("["); Node temp = first; while(temp != null){ sb.append(temp.element+","); temp = temp.next; } sb.setCharAt(sb.length()-1, ']'); return sb.toString(); } public static void main(String[] args) { SxtLinkedList05<String> list = new SxtLinkedList05<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); //list.remove(5); //list.add(3,"老高"); //list.add(0,"老陳"); list.add(5,"凡凡"); System.out.println(list); System.out.println(list.get(1)); } }