1. 程式人生 > >Java實現常見的資料結構

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 }