我似乎无法理解此类作业中的逻辑错误。我要使用链接列表进行堆栈。外部类和内部类应在UserStack中实现。 UserStack实现教师提供的MyStack。 StackApp存放主程序。
它编译并运行。它正确要求输入一个整数。如果有要删除的内容将删除,并尝试窥视是否有要显示的内容。但它始终表示已删除或显示数字0。
我是否需要尝试做toString覆盖?我问我的教授,他告诉我像其他学生一样去Google。
MyStack.java
public interface MyStack
{
public void push (int item);
public int pop ();
public int peek ();
public boolean isEmpty ();
}
UserStack.java
import java.util.NoSuchElementException;
public class UserStack implements MyStack
{
private class Node
{
public int value;
public Node link;
public Node(int data)
{
data = value;
}
}
private Node head = null;
public void push (int item)
{
Node newHead = new Node(item);
newHead.link = head;
head = newHead;
}
public int pop ()
{
if(isEmpty())
throw new NoSuchElementException();
int tmp = head.value;
head = head.link;
return tmp;
}
public int peek ()
{
if(isEmpty())
throw new NoSuchElementException();
int tmp = head.value;
return tmp;
}
public boolean isEmpty ()
{
return head == null;
}
}
StackApp.java
import java.util.Scanner;
class StackApp
{
UserStack stack = new UserStack();
public void displayMenu()
{
System.out.println ("1) Add an integer to the list\n" +
"2) Remove last integer entered\n" +
"3) Look at last integer entered\n" +
"0) Exit the program");
System.out.print ("Selection: ");
}
public StackApp()
{
int option;
Scanner input = new Scanner(System.in);
do{
displayMenu();
option = input.nextInt();
switch (option)
{
case 1:
int number;
System.out.println("Enter integer to add: ");
number = input.nextInt();
stack.push(number);
break;
case 2:
int number2 = stack.pop();
System.out.println("Interger removed: " + number2);
break;
case 3:
int number3 = stack.peek();
System.out.println("Next Interger: " + number3);
break;
case 0:
System.out.println("Goodbye");
break;
default:
System.err.println("Unrecongized choice");
break;
}
}while(option != 0);
}
public static void main(String[] args)
{
new StackApp();
}
}
最佳答案
您永远不会设置新项目的value
。