Home > Mobile >  how to implement a stack with two numbers inside each cell
how to implement a stack with two numbers inside each cell

Time:12-06

given a class TwoNumbers :

public class TwoNumbers{ private int num1, num2; public TwoNumbers (int num1, int num2){ this.num1 = num1; this.num2 = num2; } }
I want to create a function public Stack<TwoNumbers> func(Stack<Integer> st); that does this: (input)st : [8,4,7,5,3,2] (output)st_final: [num1=5 | num2=7 , num1=3 | num2=4 , num1=2 | num2=8 ]

i managed to do this so far:

public static void main(String[] args) {
    Stack<Integer> st = new Stack<Integer>();
    st.push(8);
    st.push(4);
    st.push(7);
    st.push(5);
    st.push(3);
    st.push(2);
    func(st);

}
public static Stack<TwoNumbers> func(Stack<Integer> st){
    Stack<Integer> st_top = new Stack<Integer>();
    Stack<TwoNumbers> st_final = new Stack<TwoNumbers>();
    int i;
    System.out.println("input st:" st);

    for(i=0;i<=st.size()/2;i  ) 
        st_top.push(st.pop());
        
    
    
    System.out.println("st_top:" st_top);
    System.out.println("st_bottom" st);
   

    return st_final;

but i have no idea how to insert the values into the st_final Stack

final output : (input)st : [8,4,7,5,3,2] (output)st_final: [num1=5 | num2=7 , num1=3 | num2=4 , num1=2 | num2=8 ]

CodePudding user response:

Here's an example of using the class TwoNumbers and the Stack class.

import java.util.*;

class TwoNumbers{
   int first, second;
   TwoNumbers(int f, int s){ first=f; second=s;}
}

public class Main{
    public static void main(String[] args) {
        Stack<TwoNumbers> s = new Stack<>();
        s.push(new TwoNumbers(1, 10));
        s.push(new TwoNumbers(2, 20));
    
        while(!s.empty()){
           TwoNumbers p = s.pop();
           System.out.println(p.first   ":"   p.second);
        }
    }
}
  • Related