4.數據結構--鏈表
阿新 • • 發佈:2018-08-18
head throw 返回 ext err 新元素 empty tostring color
1.什麽是鏈表
優點:不需要處理固定容量的問題
缺點:喪失了隨機訪問的能力
2.數組和鏈表的對比
3.在鏈表頭添加元素
4.在鏈表中間添加元素
5.鏈表中添加節點的代碼實現
public class LinkedList<E> { private class Node{ public E e; public Node next; public Node(E e,Node next){ this.e = e; this.next = next; }public Node(E e){ this(e,null); } public Node(){ this(null,null); } @Override public String toString(){ return e.toString(); } } private Node head; int size; public LinkedList(){ head = null; size =0; } //獲取鏈表中的元素個數 public int getSize(){ return size; } //返回鏈表是否為空 public boolean isEmpty(){ return size == 0; } //在鏈表頭添加新的元素e public void addFirst(E e){ // Node node = new Node(e); // node.next = head; // head = node; head= new Node(e,head); size ++; } //在鏈表的index位置添加新元素e public void add(int index,E e){ if(index < 0 || index > size) throw new IllegalArgumentException("Add failed.Illegal index."); if(index == 0) addFirst(e); else{ Node prev = head; for(int i = 0;i < index -1;i ++) prev =prev.next; // Node node =new Node(e); // node.next = prev.next; // prev.next = node; prev.next =new Node(e,prev.next); size ++; } } //在鏈表末尾添加新的元素e public void addLast(E e){ add(size,e); } }
6.使用鏈表的虛擬頭結點
public class LinkedList<E> { private class Node{ public E e; public Node next; public Node(E e,Node next){ this.e = e; this.next = next; } public Node(E e){ this(e,null); } public Node(){ this(null,null); } @Override public String toString(){ return e.toString(); } } private Node dummyHead; private int size; public LinkedList(){ dummyHead = new Node(null,null); size =0; } //獲取鏈表中的元素個數 public int getSize(){ return size; } //返回鏈表是否為空 public boolean isEmpty(){ return size == 0; } //在鏈表的index位置添加新元素e public void add(int index,E e){ if(index < 0 || index > size) throw new IllegalArgumentException("Add failed.Illegal index."); Node prev = dummyHead; for(int i = 0;i < index;i ++) prev =prev.next; prev.next =new Node(e,prev.next); size ++; } //在鏈表頭添加新的元素e public void addFirst(E e){ add(0,e); } //在鏈表末尾添加新的元素e public void addLast(E e){ add(size,e); } }
4.數據結構--鏈表