Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
A method which returns a new reveresed Singly Linked List using a stack in Java, keeping the same elements but printing them out in reversed order

So for example if in a list with 2 elements, where letter A is the first element and letter B is the second element, this method would return a new list with the same elements but reversed, so B first and A second. Unfortunately in this case it doesn't work and i get an EmptyStackException instead. It also says that the return value of the method is never used, not sure what to have as return statement for it to work.Can someone tell me where is the error in my code exactly, or maybe just point me in the right direction. Thanks in advance !

Here is my code :

  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 i added a second temporary variable ,changed the return statement and used a toString() method in main to print it out.It works fine even with more than 2 elements, but when i hover with my mouse on reverse(), the IDE still says that the return value of the method is never used ?! Here is what i updated:

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());
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You should not return anything, and you should update the temp when popping out element from the stack. Something like:

 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;
}

Your IDE complains because:

List.reverse();

you did not set the return of the reverse method to anything, for instance:

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

But again, you do not need to return anything.

over 4 years ago · Santiago Trujillo Relatório

0

Not sure why you have all that code or are trying to use a stack. You already seem to have used the reverse library method so why not use that instead of re-inventing the wheel?

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

Or am I missing the point?

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda