Java Collections (LIFO Structure)

前端 未结 6 1478
栀梦
栀梦 2020-12-05 06:55

I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Dequ

6条回答
  •  悲哀的现实
    2020-12-05 07:30

    Deque & LinkedList

    Just for the sake of completeness I'm providing an example using Deque interface and a LinkedList implementation.

        Deque deque = new LinkedList<>();
        deque.add("first");
        deque.add("last");
    
        // returns "last" without removing it
        System.out.println(deque.peekLast());
    
        // removes and returns "last"
        System.out.println(deque.pollLast());
    

    Backing up a Deque by a LinkedList is great for performance, since inserting and removing elements from it is done in constant time (O(1)).

    Using a LinkedList alone:

        LinkedList list = new LinkedList<>();
        list.add("first");
        list.add("last");
    
        // returns "last" without removing it
        System.out.println(list.getLast());
    
        // removes and returns "last"
        System.out.println(list.removeLast());
    

提交回复
热议问题