我需要帮助在堆栈中添加推入的元素。我希望下面的returnItems方法将压入的元素返回到堆栈中,如果它是回文,则用于与下面的字符串进行比较。
该字符串的每个字符都被压入堆栈:abcdef
这是returnItems方法。如何修改加粗部分以获得返回值(例如:上面示例中的fedcba):
public T returnItems() {
Node<T> temp = top;
T value = null;
if (top == null) { // checks if stack is empty
System.out.println("Stack is empty");
value = null;
}
System.out.println("Elements: ");
while (temp.getInfo() != null) {
value = temp.getInfo(); // get the current character
// How do I append the characters that the value variable temporarily holds
// for each loop
***value = (T) (value + " " + temp.getLink());*** // append it to the current character
if (temp.getLink() == null) { // if the next link is null, the loop will break
break;
}
temp = temp.getLink(); // else, get the next link
}
return value;
}
当您对堆栈上的两个元素使用T时(可以为char
使用Character
),结果是String
,必须假设您有Stack<String>
左右,因此有Node<String>
。
public String returnItems() {
String reversed = ""; // Better a StringBuilder.
while (top != null) {
String ch = top.getInfo(); // get the current character
reversed = reversed + ch;
top = top.getLink(); // or `pop()` or such.
}
return reversed;
}
这意味着returnItems
必须而不是在Stack类本身中,因为回文仅用于字符堆栈(Stack用法)。我希望看到:
class Stack<T> {
T top() { ... }
boolean isEmpty() { ... }
T pop() { ... }
void push(T item) { ... }
}
Stack<Character> charStack = new Stack<>();
public String returnItems() {
String reversed = ""; // Better a StringBuilder.
while (!charStack.isEmpty()) {
char ch = charStack.pop(); // get the current character
reversed += ch;
}
return reversed;
}