Java实现常见的数据结构
1、普通队列
1 import java.util.LinkedList; 2 3 4 public class MyQueue<E> { 5 6 private LinkedList<E> list = new LinkedList<E>(); 7 8 public void enqueue(E e) { 9 list.addLast(e); 10 } 11 12 public E dequeue() { 13 return list.removeFirst(); 14 } 15 16 public int getSize() { 17 return list.size(); 18 } 19 20 public String toString() { 21 return "Queue" + list.toString(); 22 } 23 24 public static void main(String[] args) { 25 MyQueue<String> myqueue = new MyQueue(); 26 myqueue.enqueue("x1"); 27 myqueue.enqueue("x2"); 28 int size = myqueue.getSize(); 29 System.out.println(size); 30 System.out.println(myqueue.dequeue()); 31 32 33 } 34 }
2、优先队列
1 public class MyPriorityQueue<E extends Comparable> { 2 private Heap<E> heap = new Heap<E>(); 3 4 public void enqueue(E newObject) { 5 heap.add(newObject); 6 } 7 8 public dequeue() { 9 return heap.remove(); 10 } 11 12 public int getSize() { 13 return heap.getSize(); 14 } 15 }
积沙成塔