今天学习了,Java中的LinkedList类。这个类需要用到链表的知识,以前一直以为,只有c/c++有链表。今天才知道,原来其他语言。也有链表,而且还是双向链表。
1 /** 2 * 自定义一个链表 3 * @author 小白 4 * 5 */ 6 public class SxtLinkedList { 7 8 private Node first; 9 private Node last; 10 11 private int size; 12 13 public void add(Object obj){ 14 Node node = new Node(obj); 15 16 if(first==null){ 17 18 first = node; 19 last = node; 20 }else{ 21 node.previous = last; 22 node.next = null; 23 24 last.next = node; 25 last = node; 26 } 27 } 28 29 @Override 30 public String toString() { 31 StringBuilder sb = new StringBuilder("["); 32 Node temp = first; 33 while(temp!=null){ 34 sb.append(temp.element + ","); 35 temp = temp.next; 36 } 37 sb.setCharAt(sb.length()-1, ']'); 38 return sb.toString(); 39 40 } 41 42 43 44 public static void main(String[] args) { 45 SxtLinkedList list = new SxtLinkedList(); 46 list.add("a"); 47 list.add("b"); 48 list.add("c"); 49 50 System.out.println(list); 51 } 52 53 }