使用堆栈测试字符串是否为回文



我正在尝试获取用户输入的单词,将其添加到堆栈中,然后检查该单词是否是回文。我正在尝试将所有内容从堆栈中弹出到一个新字符串上,然后比较字符串。我相信我目前的问题是我的 pop(( 函数实际上并没有返回值。它实际上只是切断了尾节点,然后在没有尾节点的情况下重新打印字符串。我想我的问题是,我如何编写我的 pop(( 函数以使其返回"popped"值?

这是我的主要方法

Scanner input = new Scanner(System.in);
Stack_Scott_Robinson<Character> myList = new Stack_Scott_Robinson<Character>(); //create a list object
System.out.println("Enter a string: ");
String s = input.next();
for (int i = 0; i < s.length(); i++){
myList.push(s.charAt(i));
}
String reverseInput = "";
while (!myList.isEmpty()){
reverseInput = reverseInput + myList.Pop();
}
if (s.equals(reverseInput)){
System.out.println("This is a palindrome");
}else{
System.out.println("This is not a palidrome");
System.out.print("Would you like to re-run code with different input string(y/n)?");
another = input.next();
}

这是我的 pop(( 方法

public void Pop()
{
Node countList = end; //set "count" node at the front of the list
int size = 0; //initialize the size variable
//moves the count node down the list and increments the size variable
while (countList != null)
{
countList = countList.next;
size++;
}
if (size == 0){ //empty list
System.out.println("error: empty list");
}else if (size == 1) //one node list
{
top = null;
end = null;
System.out.println("list is now empty");
}
else{
Node current = end;//set a current node at the front of the list
for (int i = 0; i<size-2; i++)//-2 because the list starts at 0 and we want the second to last position
{
current = current.next;//moves the current node down the list until it is 
} 
Node temporary = current.next;  //the second to last position
Node temp = top;//create a new node space
top = current;//set the new node equal to the second to last position
top.next = null;//sets the node as the tail
}
}   

以下是java.util.Vector的做法(java.util.Stack扩展了Vector(

public synchronized E pop() {
E       obj;
int     len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}

public synchronized void removeElementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
modCount++;
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}

在 pop 方法中,您可以看到我们知道要删除什么对象,因为他们使用 peek(( 获取它;然后他们只是删除向量末尾的元素。希望这有所帮助。我不确定你如何在引擎盖下代表你的堆栈,所以没有它,我真的不能给你一个更好的答案。

最新更新