Question d’entretien chez Cisco

How to reverse a linked list? (in 2 different ways)

Réponse à la question d'entretien

Utilisateur anonyme

11 nov. 2012

Assume a singly linkedList LinkedList reverse1(LinkedList list){ if(list.size() == 0){return list;} LinkedList list1 = new LinkedList();//constructs a new linkedList cursor = list.head.next; //set the cursor to the first element while (cursor.hasNext()){ list1.insertBefore(cursor.getItem()); cursor = cursor.next; } list1.insetBefore(cursor.getItem()); return list1; } If you want to know more about how to implement InsertBefore, email me: peng.jason03265@gmail.com, I will give you my code in Python. Another way is to do it without InsertBefore method in the linkedList, but will take O(2n) time (less efficient, but does not matter that much since modern computers can handle very fast). I'm a bit lazy to write out the code for this one, basically you walk through the list and insert them into a stack, and you construct a new list and pop every element from that stack. Then you return the new list after the stack is empty.

1