【问题标题】:how to implement a stack with two numbers inside each cell如何实现每个单元格内有两个数字的堆栈
【发布时间】:2022-12-20 09:01:20
【问题描述】:

给定一个类两个数字:

public class TwoNumbers{ private int num1, num2; public TwoNumbers (int num1, int num2){ this.num1 = num1; this.num2 = num2; } }
我想创建一个函数 public Stack<TwoNumbers> func(Stack<Integer> st); 来执行此操作: (输入)st:[8,4,7,5,3,2] (输出)st_final: [num1=5 | num2=7 , num1=3 | num2=4 , num1=2 | num2=8 ]

到目前为止我设法做到了:

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;

但我不知道如何将值插入 st_final 堆栈

最终输出: (输入)st:[8,4,7,5,3,2] (输出)st_final: [num1=5 | num2=7 , num1=3 | num2=4 , num1=2 | num2=8 ]

【问题讨论】:

  • 在 for 循环之后,stst_top 应该具有相同的大小。 (输入一些代码来检查这一点只是为了确定。)然后编写第二个循环 st.size() 次的 for 循环。在第二个 for 循环中,pop stst_top。使用从这两个 pop 中获得的两个整数来创建 Two Numbers 的实例。将 TwoNumbers 的实例推送到 st_final
  • 将堆栈分成两个相等的部分后(您应该在这样做之前验证堆栈的大小是否相等),您将需要创建数字对并将它们压入新堆栈。您可以使用 new TwoNumbers(n1, n2) 创建对,然后使用 push 函数将对添加到新堆栈中
  • @ThomasBehr for(i=0;i&lt;=st.size();i++) { new TwoNumbers(st_top.pop(),st.pop()); st_final.push(TwoNumbers); } 它为这两个数字提供了一个空值,我是不是遗漏了什么? @NadavBarghil

标签: java class generics queue stack


【解决方案1】:

下面是使用类 TwoNumbers 和 Stack 类的示例。

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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2010-09-09
    • 2019-02-22
    • 2010-10-15
    • 2014-04-21
    相关资源
    最近更新 更多