Same: Both of Stack and Dequeu can be a stack.

Differences:

1. Deque is a LinkedList, Stack is a Stack.

2. Dequeu can getFirst() and getLast(), but Stack cannot.

3. Stack is stored "first in first pushed", only when pop() it, the last pushed element is returned. While Deque is stored "first in last pushed", when pop() it, the first element in the list shall be returned.

Take an example:

Stack:

        Stack<Integer> stk = new Stack();
        stk.push(1);
        stk.push(2);
        stk.push(3);
        for(int i: stk)
            System.out.println(i);
        while (!stk.isEmpty()) {
            System.out.println(stk.pop());
        }

The output is 

1
2
3
3
2
1

Deque:

        Deque<Integer> deque = new LinkedList<>();
        deque.push(1);
        deque.push(2);
        deque.push(3);
        System.out.println("--------");
        System.out.println(deque.getFirst());
        System.out.println(deque.getLast());
        System.out.println("--------");
        for(int i: deque)
            System.out.println(i);
        while (!deque.isEmpty()) {
            System.out.println(deque.pop());
        }

The output is:

--------
3
1
--------
3
2
1
3
2
1

When use Stack and Deque, don't mix match them. Unless you need to getFirst() or getLast(), always using Stack is safer.

 

posted on 2022-02-05 09:39  阳光明媚的菲越  阅读(29)  评论(0编辑  收藏  举报