gpt4 book ai didi

java - 用Java制作一个堆栈方法

转载 作者:行者123 更新时间:2023-12-01 13:48:52 26 4
gpt4 key购买 nike

是否有任何简单的方法可以让堆栈显示出来,然后在“PrintAndEmpty”方法中清空堆栈?我需要 PrintAndEmpty 方法中的 print 和empty,而不是 main 方法。代码是:

 import java.util.*;
class Stack<E> implements StackInterface<E> {
private ArrayList<E> items;

public Stack() { // default constructor; creates an empty stack
items = new ArrayList<E>(); // initial capacity is 10
}

public Stack(int initialCapacity) {
//one argument constructor, creates a stack with initial capacity initialCapacity
items = new ArrayList<E>(initialCapacity);
}

public void push(E x) {
items.add(x); //uses the ArrayList method add(E o)
}

public E pop() {
if (empty()) // determine whether or not there is an item to remove
return null;
return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}

public boolean empty() {
return items.isEmpty();//uses the ArrayList method isEmpty()
}

public int size() {
return items.size(); //uses the ArayList method size()
}

public E peek() {
if (empty()) // determine whether or not there is an item on the stack
return null;
return items.get(items.size()-1); //uses the ArrayList method get(int i)
}

public void PrintAndEmpty()
{
// I want to print then empty the stack here, not in the main method.
}

主要方法

 public static void main (String[] args)  // for demonstration only
{
Stack<Student> s = new Stack<Student>();
// push five Student references onto s
s.push(new Student("Spanky", "1245"));
s.push(new Student("Alfalfa", "1656"));
s.push(new Student("Darla", " 6525"));
s.push(new Student("Stimie", "1235"));
s.push(new Student("Jackie", "3498"));


// The data below is what I am trying to put in the PrintAndEmpty method


while(!s.empty())
System.out.println(s.pop().getName());
System.out.println();
System.out.println("The size of the stack is now "+s.size());

}

用于测试目的的学生类(class):

 public class Student
{
private String name;
private String id;

public Student()
{
name = "";
id = "";
}

public Student (String n, String idNum)
{
name = n;
id = idNum;
}

public String getName()
{
return name;
}

public String getID()
{
return id;
}

public void setName(String n)
{
name = n;
}

public void setID( String idNum)
{
id = idNum;
}

public boolean equals(Object o) // name and id are the same
{
return ( (((Student)o).name).equals(name) &&
(((Student)o).id).equals(id) );
}

}

对于让它发挥作用我完全没有想法。如果有人有建议,请告诉我。我将不胜感激!

最佳答案

不确定您为什么要这样做,但您可以这样做:

// PrintAndEmpty 'this' stack.
public void PrintAndEmpty()
{
// The condition to check - e.g. 'this' stack.
while(!this.empty()) {
// Pop from the stack - e.g. 'this' stack.
System.out.println(this.pop().getName());
}
}

关于java - 用Java制作一个堆栈方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com