手動實現LinkedList,增加remove方法 (3)
阿新 • • 發佈:2019-02-16
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; } }
remove方法的實現改變前後元素的即可
package com.jianshun; /** * 自定義一個連結串列 * 增加remove * @author Administrator * */ public class SxtLinkedList03 { private Node first; private Node last; private int size; //[] //['a','b','c'] public void add(Object obj){ Node node = new Node(obj); 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){ 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--; } } //根據下標獲取節點(程式碼重用) public Node getNode(int 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 Object get(int index){ if(index <0 || index >size - 1){ throw new RuntimeException("索引數字不合法:"+index); } Node temp = getNode(index); return temp !=null ? temp.element : null; } @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) { SxtLinkedList03 list = new SxtLinkedList03(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); list.remove(5); System.out.println(list); } }