Question d’entretien chez Amazon

How would you reverse a linked list in Java?

Réponses aux questions d'entretien

Utilisateur anonyme

15 août 2009

First answer is incorrect (no such method). 2nd answer is correct. I've seen this question before where the expected answer is to manipulate the list.

2

Utilisateur anonyme

17 août 2009

public class LinkedListElement { private E _element; private LinkedListElement _next; public LinkedListElement(E element) { _element = element; _next = null; } public LinkedListElement(E element, LinkedListElement next) { _element = element; _next = next; } public E get() { return _element; } public LinkedListElement next() { return _next; } public void setNext(LinkedListElement next) { _next = next; } public static LinkedListElement reverse(LinkedListElement e) { if (e == null) { return null; } LinkedListElement current = e; LinkedListElement next = e.next(); e.setNext(null); while (next != null) { LinkedListElement forward = next.next(); next.setNext(e); e = next; next = forward; } return e; } }

1

Utilisateur anonyme

11 févr. 2014

public void reverse(ReverseSinglyLinkedList singlyLinkedList){ if(singlyLinkedList.isEmpty()){ return; } Node currentNode = head; Node nextNode = head.nextNode; Node markNode; head.nextNode = null; while(nextNode!=null){ markNode = nextNode.nextNode; nextNode.nextNode = currentNode; currentNode = nextNode; nextNode = markNode; } head = currentNode; }

Utilisateur anonyme

6 mai 2009

List.reverse()

3