Use LinkedList to implement Stack and Queue

Stack:

Code:

public class MyStack {
    private LinkedList list = new LinkedList();

    /**
     * push the stack
     */
    public void push(Object o) {
        list.addFirst(o);
    }

    /**
     * pop, delete
     */
    public Object pop() {
        return list.removeFirst();
    }

    /**
     * pop, do not delete
     */
    public Object peek() {
        return list.getFirst();
    }


    public boolean isEmpty() {
        return list.isEmpty();
    }

    public static void main(String[] args) {
        MyStack myStack = new MyStack ();
        myStack.push("one");
        myStack.push("two");
        myStack.push("three");

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

        System.out.println(myStack.isEmpty());
    }
}

Compile and run:

Queue:

Its specific implementation:

public class MyQueue {
    private LinkedList list = new LinkedList();

    /**
     * Insert from the end
     */
    public void put(Object o) {
        list.addLast(o);
    }

    /**
     * Take out from the head
     */
    public Object get() {
        return list.removeFirst();
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.put("one");
        myQueue.put("two");
        myQueue.put("three");

        System.out.println(myQueue.get());
        System.out.println(myQueue.get());
        System.out.println(myQueue.get());

        System.out.println(myQueue.isEmpty());
    }
}

Compile and run:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325380909&siteId=291194637