本次内容:linkedlist()
此次是承接上次arraylist(),自己实现linkedlist()(内容较少)
1 package list; 2 /** 3 * 自定义linkedlist类 4 * @author acer 5 * 6 */ 7 public class mylinkedlist { 8 private Node first; 9 private Node last; 10 private int size; 11 public void add(Object obj) 12 { 13 Node n=new Node(); 14 if(first==null) 15 { 16 n.setPrevious(null); 17 n.setObj(obj); 18 n.setNext(null); 19 first=n; 20 last=n; 21 } 22 else 23 { 24 n.setPrevious(last); 25 n.setObj(obj); 26 n.setNext(null); 27 last.setNext(n); 28 last=n; 29 } 30 size++; 31 } 32 public void add(int index,Object obj) 33 { 34 Node temp=null; 35 Node newNode=new Node(); 36 newNode.setObj(obj); 37 if(first!=null) 38 { 39 temp=first; 40 for(int i=0;i=size)100 {101 try {102 throw new Exception();103 } catch (Exception e) {104 e.printStackTrace();105 }106 }107 }108 public int size()109 {110 return size;111 }112 public static void main(String[] args)113 {114 mylinkedlist list=new mylinkedlist(); 115 list.add("aaa");116 list.add("bbb");117 list.add("ccc");118 list.add("ddd");119 System.out.println(list.size());120 System.out.println(list.get(1));121 list.removefirst();122 System.out.println(list.get(0));123 }124 }125 126 127 class Node128 {129 private Node previous;130 private Object obj;131 private Node next;132 public Node()133 {134 }135 public Node(Node previous, Object obj, Node next) {136 super();137 this.previous = previous;138 this.obj = obj;139 this.next = next;140 }141 public Node getPrevious() {142 return previous;143 }144 public void setPrevious(Node previous) {145 this.previous = previous;146 }147 public Object getObj() {148 return obj;149 }150 public void setObj(Object obj) {151 this.obj = obj;152 }153 public Node getNext() {154 return next;155 }156 public void setNext(Node next) {157 this.next = next;158 }159 }
运行结果:
4
bbbbbb