一种方法,在java中使用堆栈返回一个新的重新排序的单链表,保留相同的元素,但按相反的顺序打印出来

bksxznpy  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(211)

例如,如果在一个包含两个元素的列表中,字母a是第一个元素,字母b是第二个元素,那么这个方法将返回一个包含相同元素但相反的新列表,因此字母b是第一个元素,字母b是第二个元素。不幸的是,在这种情况下它不起作用,我得到了一个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();
-----------------

update--->ok我添加了第二个临时变量,更改了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());
}
bwntbbo3

bwntbbo31#

不知道为什么你有那么多代码或者试图使用堆栈。你好像已经用过了 reverse 图书馆的方法,所以为什么不使用,而不是重新发明车轮?

LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
Collections.reverse(list);

还是我没抓住重点?

lf3rwulv

lf3rwulv2#

您不应该返回任何内容,并且应该在从堆栈中弹出元素时更新temp。比如:

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();

您没有将反向方法的返回设置为任何值,例如:

LinkedNode<E> tmp = List.reverse();

不过,你不需要归还任何东西。

相关问题