-2
有沒有人知道如何編寫方法toStringRec遞歸地打印堆棧? 下面是類和主要方法文件 我有蜜蜂試圖運行它幾小時,但未能完成。遞歸棧打印方法
public class IntLinkedStack
{
private IntNode top;
public static int temp = 0;
public boolean isEmpty()
{
if (top == null)
return true;
else
return false;
}
public int size()
{
return sizeRec(top);
}
private int sizeRec(IntNode t)
{
IntNode aux = t;
if (aux != null){
temp++;
sizeRec(aux.next);
}
return temp ;
}
public String toString()
{
return toStringRec(top);
}
// WRITE THIS METHOD: toStringRec
private String toStringRec(IntNode t)
{
}
public int peek()
{
if (isEmpty())
throw new RuntimeException("Peek attempted on empty stack");
else
return top.data;
}
public void push(int m)
{
IntNode temp;
temp = new IntNode();
temp.data = m;
temp.next = top;
top = temp;
}
public int pop()
{
int value;
if (isEmpty())
throw new RuntimeException("Pop attempted on empty stack");
else
{
value = top.data;
top = top.next;
return value;
}
}
}
接下來的主要方法
import java.util.Scanner;
public class ITDIntLinkedStack
{
public static void displayMenu()
{
System.out.println("\n(1) display menu");
System.out.println("(2) check isEmpty");
System.out.println("(3) push");
System.out.println("(4) peek");
System.out.println("(5) pop");
System.out.println("(6) empty the stack");
System.out.println("(7) size");
System.out.println("(8) toString");
System.out.println("(0) quit");
}
public static void main(String [] args)
{
if (true || false)
System.out.println("YES");
Scanner kbd = new Scanner(System.in);
IntLinkedStack x = new IntLinkedStack();
int choice = 1;
int value;
System.out.println("Here are your choices: ");
displayMenu();
System.out.print("\nEnter your choice#: ");
choice = kbd.nextInt();
while (choice >= 1 && choice <= 8)
{
if (choice == 1)
displayMenu();
else if (choice == 2)
System.out.println("Stack isEmpty?: " + x.isEmpty());
else if (choice == 3)
{
System.out.print("Enter value to push: ");
value = kbd.nextInt();
x.push(value);
System.out.println("Pushed value " + value + ".");
}
else if (choice == 4)
{
value = x.peek();
System.out.println("Peeked at top of stack: " + value + ".");
}
else if (choice == 5)
{
value = x.pop();
System.out.println("Popped " + value + " off the stack.");
}
else if (choice == 6)
{
System.out.println("Emptying stack...");
while (!x.isEmpty())
System.out.println("Popped " + x.pop());
System.out.println("Stack is now emptied.");
}
else if (choice == 7)
System.out.println("Size is " + x.size());
else if (choice == 8)
{
System.out.println("Here is a view of the stack: ");
System.out.println(x.toString());
}
System.out.print("\nEnter your choice#: ");
choice = kbd.nextInt();
} // end while (choice >= 1 && <= 9)
System.out.println("Bye!");
} // end public static void main(String [] args)
} // end public class ITDArrayStack
而在這幾個小時,你沒能寫出toStringRec方法單行?你知道遞歸的意思嗎? – ElDuderino 2014-09-25 11:34:31
剛剛接觸java ... – 2014-09-26 21:51:15
感謝您的幫助 – 2014-09-26 21:51:39