Sunday, March 11, 2018

Java Stack, Queue(Deque), PriorityQueue



import com.sun.jmx.remote.internal.ArrayQueue;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;


public class Test {

    public static void main(String [] args) {
        testStack();
        testQueue();
        testPriorityQueue();
    }

    public static void testStack() {
        System.out.println("------- test stack -------");
        Stack<Integer> s = new Stack<Integer>();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);

        System.out.println(s);
        System.out.println("s.peek: " + s.peek());

        s.pop();
        System.out.println(s);


        System.out.println("s.peek: " + s.peek());
        System.out.println(s);


        s.pop();
        System.out.println(s);


        s.pop();
        System.out.println(s);


        s.pop();
        System.out.println(s);

        try {
            s.pop();
            System.out.println(s);
        } catch (EmptyStackException ex) {
            System.out.println("exception: " + ex.getMessage());
        }

    }

    public static void testQueue() {
        System.out.println("------- test queue -------");

        Queue<Integer> q = new ArrayDeque<>();
        q.add(1);
        q.add(2);
        q.add(3);
        q.add(4);
        System.out.println(q);

        while(!q.isEmpty()) {
//            System.out.println(q.peek());            Integer removed = q.remove();
            System.out.println("removed: " + removed);
            System.out.println(q);
        }
    }

    public static void testPriorityQueue() {
        System.out.println("------- test queue -------");

        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(2);
        pq.add(1);
        pq.add(4);
        pq.add(3);

        System.out.println(pq);

        while(!pq.isEmpty()) {
            System.out.println("pq top: " + pq.peek());
            pq.poll();
            System.out.println("pq: " + pq);
        }
    }
}

No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...