먼저 코드가 길지만 toString 메서드에 대해서만 신경이 쓰입니다. 나는 모든 경우를 위해 붙여 넣었다.첫 번째 노드를 스택에 입력하지 않음 (toString)
코드는 입력 한 요소가 스택 맨 위에있는 요소보다 작은 지 여부를 확인합니다. 나는 그 부분을 알아 냈다. 저장된 입력을 인쇄하기 위해 toString 메서드를 호출하면 스택에 추가 된 첫 번째 노드가 인쇄되지 않습니다. 그러나 나머지 입력을 모두 인쇄합니다.
testing
test
te
t
What its currently outputing:
t te test
What it needs to output:
t te test testing
홈페이지 :
import java.util.*;
public class Stack {
public static void main(String args[]) {
int loopInt = 1;
PyramidStack<String> stringStack = new PyramidStack<String>();
PyramidStack<Integer> intStack = new PyramidStack<Integer>();
System.out
.println("This program will save some of the strings you enter. ");
System.out
.println("Can you predict which ones will be saved? (Enter nothing to quit.)");
Scanner sc = new Scanner(System.in); // Opens Scanner for keyboard input
try {
do {
System.out.print("Enter a String: ");
String input = sc.nextLine();
if (input.length() > 0) {
if (stringStack.size() == 0) {
intStack.push(input.length());
stringStack.push(input);
System.out.println("String Saved");
}
else if (input.length() < intStack.peek()) {
stringStack.push(input);
intStack.push(input.length());
System.out.println("String Saved");
}
else {
System.out.println("String NOT saved. Already saved "
+ intStack.countBefore(input.length())
+ " strings that should come before this one.");
}
} else {
System.out.println();
System.out.println(stringStack.toString());
System.out.println(intStack.toString());
loopInt--;
sc.close();
}
} while (loopInt > 0);
} catch (NullPointerException e) {
System.out.println("No strings have been entered. Ending the program.");
}
}
}
PyramidStack 방법 :
import java.util.*;
import java.lang.Comparable;
public class PyramidStack<E extends Comparable<E>> extends Stack<E> {
@Override
public void push(E item) throws IllegalArgumentException {
if (super.size == 0) {
super.push(item);
}
else if(item.compareTo(super.peek()) <= 0) {
super.push(item);
}
else {
System.out.println("String NOT saved. " + countBefore(item) + " strings that should come before this one.");
}
}
@Override
public String toString() {
Node<E> node;
node = this.top;
String s = "";
while(node.getNext() != null){
s += node.getData() + " ";
node = node.getNext();
}
return s;
}
public int countBefore(E item) {
Node<E> node;
node = this.top;
int i = 0;
while(node.getNext() != null){
if(item.compareTo(super.peek()) <= 0) {
node = node.getNext();
}
else{
i++;
node = node.getNext();
}
}
return i;
}
}
스택 방법과 노드 방법 아래 의견 사용자가 다음과 같은 입력 경우를 예로들 수있다.
노드 및 스택 클래스의 붙여 넣기 bin.http : //pastebin.com/N4Q1j6Tn –