因此,例如,如果在包含 2 个元素的列表中,其中字母 A 是第一个元素,字母 B 是第二个元素,此方法将返回一个包含相同元素但颠倒的新列表,因此 B 在前,A 在后。不幸的是,在这种情况下它不起作用,我得到的是 EmptyStackException。它还说从未使用过该方法的返回值,不确定返回语句有什么让它起作用。有人能告诉我我的代码中的错误到底在哪里,或者只是指出正确的方向。提前致谢!
这是我的代码:
public LinkedList<E> reverse() throws EmptyListException {
Stack<LinkedNode<E>> stack = new Stack<>();
LinkedNode<E> temp = head;
while(temp != null){
stack.push(temp);
temp = temp.next;
}
temp = stack.peek();
head = temp;
stack.pop();
while(!stack.isEmpty()){
temp.next = stack.peek();
stack.pop();
temp =temp.next;
}
temp.next = null;
return stack.peek();
}
public static void main(String[] args){
LinkedList<String> List = new LinkedList<>();
List.add("A");
List.add("B");
List.reverse();
-----------------
更新---> 好的,我添加了第二个临时变量,更改了 return 语句并在 main 中使用了 toString() 方法将其打印出来。即使有 2 个以上的元素也能正常工作,但是当我将鼠标悬停在 reverse() 上时,IDE仍然说该方法的返回值从未被使用过?! 这是我更新的内容:
LinkedNode<E> temp2 = temp;
while(!stack.isEmpty()){
temp.next = stack.peek();
stack.pop();
temp =temp.next;
}
temp.next = null;
head = temp2;
return temp2;
public static void main(String[] args) {
LinkedList<String> List = new LinkedList<>();
List.add("A");
List.add("B");
List.add("C");
List.add("D");
List.add("E");
List.add("F");
List.reverse();
System.out.println(List.toString());
}
最佳答案
你不应该返回任何东西,你应该在从堆栈中弹出元素时更新温度。像这样的东西:
public void reverse() throws EmptyListException {
if(head == null)
throw new EmptyListException
Stack<LinkedNode<E>> stack = new Stack<>();
LinkedNode<E> temp = head;
while(temp != null){
stack.push(temp);
temp = temp.next;
}
head = stack.peek();
while(!stack.isEmpty()){
temp = stack.peek();
stack.pop();
temp = temp.next;
}
temp.next = null;
}
您的 IDE 提示是因为:
List.reverse();
您没有将 reverse 方法的返回设置为任何内容,例如:
LinkedNode<E> tmp = List.reverse();
但同样,您不需要返回任何东西。
关于java - 一种在 Java 中使用堆栈返回新的反向单链表的方法,保留相同的元素但以相反的顺序打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65062664/