gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:29:49 25 4
gpt4 key购买 nike

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

这是我的主要方法

 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() 获取它;然后他们只是删除 vector 末尾的元素。希望这有帮助。我不确定你在幕后如何代表你的堆栈,所以如果没有这个,我真的无法给你更好的答案。

关于java - 使用堆栈测试字符串是否为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com