Home > OS >  Changing the order of a stack in Java
Changing the order of a stack in Java

Time:09-18

I am looking for a way to change the order of the elements in a Java stack so that the even numbers are under the odd numbers.

For example : 5, 2, 6, 7, 1, 4, 3 it becomes this 5, 7, 1, 3, 2, 6, 4.

Here is my code currently, I am stuck to find how to change the order :

public static void main(String[] args) {

    Stack<Integer> p = new Stack<>();

    p.push(3);
    p.push(4);
    p.push(1);
    p.push(7);
    p.push(6);
    p.push(2);
    p.push(5);
    
    ListIterator<Integer> ListIterator = p.listIterator(p.size());  
     
    while (ListIterator.hasPrevious())   
    {  
    Integer i = ListIterator.previous();  
    System.out.println(i);  
    } 
    
}

Thanks for your help !

CodePudding user response:

Stack is subclass of AbstractList, so you can use List.sort() by providing custom Comparator.

public class Temp {

    public static void main(String[] args) {
        Stack<Integer> p = new Stack<>();

        p.push(3);
        p.push(4);
        p.push(1);
        p.push(7);
        p.push(6);
        p.push(2);
        p.push(5);

        p.sort((a, b) -> {
            if (a % 2 == 0 && b % 2 == 0) {
                return 0;
            }
            if (a % 2 == 0) {
                return 1;
            }
            if (b % 2 == 0) {
                return -1;
            }
            return 0;
        });
        System.out.println(p);
    }
}

For the initial stack of - [3, 4, 1, 7, 6, 2, 5] this results in - [3, 1, 7, 5, 4, 6, 2].

CodePudding user response:

There are many ways to accomplish the task of separating odd and even elements.

I suspect that the purpose of this challenge is getting familiar with the Stack data structure and its basic operations.

So here's a solution with two addition Stacks, one to accumulate the odd elements, another for even.

Stack<Integer> numbers = new Stack<>();
        
numbers.push(3);
numbers.push(4);
numbers.push(1);
numbers.push(7);
numbers.push(6);
numbers.push(2);
numbers.push(5);
        
Stack<Integer> odd = new Stack<>();
Stack<Integer> even = new Stack<>();
        
while (!numbers.isEmpty()) {
    Integer next = numbers.pop();
    if (next % 2 == 0) even.push(next);
    else odd.push(next);
}
        
numbers.addAll(odd);
numbers.addAll(even);
    
System.out.println(numbers);

Output:

[5, 7, 1, 3, 2, 6, 4]

Note:

  • Class Stack is legacy, and shouldn't be used (unless it's a requirement of your assignment). When you need an implementation of the stack data structure in Java the recommended alternative is to use implementations of the Deque interface.
  • Try to use more meaningful names than p. It's a good habit because it makes the code easier to read and maintain. Single-letter variable are acceptable only rare cases, like variables defined within a for-loop. Also see Java Language Naming Conventions.
  • Related