简体   繁体   中英

How to reverse order Stack and Queue in Java

I want to reverse the order of my output using stack and queues in Java.

Here is my code:

import java.util.*;

public class Books {
    public static void main(String[] args) {
        Queue<String> book = new LinkedList<String>();
        Stack<String> Title = new Stack<>();
        Scanner user = new Scanner(System.in);

        System.out.println("Enter four book titles.");
        int b = 4;
        for (int i = 1; i <= b; i++) {
            System.out.print("Book " + i + ": ");
            String Enter = user.nextLine();
            book.offer(Enter);
        }

        System.out.println("New order of books:");
        System.out.println(book);

    }
}

Here is the output of this code.

Enter four book titles.
Book 1: wew1
Book 2: wew2
Book 3: wew3
Book 4: wew4
New order of books:
[wew1, wew2, wew3, wew4]

What I was trying to is to make it in reverse order. But I don't know what to do.

You can try to add the book in the Queue and add them to Stack then printing using pop() operation.

It's recommended to use ArrayDeque implementation when you want to use a Stack

    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        Scanner user = new Scanner(System.in);

        System.out.println("Enter four book titles.");
        int b = 4;
        for (int i = 1; i <= b; i++) {
            System.out.print("Book " + i + ": ");
            String Enter = user.nextLine();
            queue.add(Enter);
        }

        ArrayDeque<String> stack = new ArrayDeque<>();
        while (!queue.isEmpty()) {
            stack.push(queue.poll());
        }

        System.out.println("New order of books:");
        while (!stack.isEmpty()) {
            System.out.print(stack.pop()+" ");
        }
        user.close();
    }

, output

Enter four book titles.
Book 1: wew1
Book 2: wew2
Book 3: wew3
Book 4: wew4
New order of books:
wew4 wew3 wew2 wew1

Use the advantage that LinkedList implements Deque (double-ended queue). Note that Deque also implements Queue (single-ended queue).

You can use the method Deque#offerFirst(E e) to insert the book at the beginning of the queue. There is no need of reversing such queue afterward. Minimal example:

Deque<String> queue = new LinkedList<>();
        
for (int i = 1; i <= 4; i++){
    queue.offerFirst("book" + i);
}

System.out.println("Reversed order of books:");
System.out.println(queue);

Output:

 Reversed order of books: [book4, book3, book2, book1]

Note 1: Consider using ArrayDeque instad of LinkedList as long as you don't need to access by an index.

Note 2: Don't use Stack as long as it is considered obsolete and deprecated .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM