Question d’entretien chez Amazon

Reverse a linked list.

Réponses aux questions d'entretien

Utilisateur anonyme

23 sept. 2012

Node ReverseLinkedList(Node head) { Node next = head.next; if (next == null) { return head; } Node revList = ReverseLinkedList(head.next); next.next = head; head.next = null; return revList; }

4

Utilisateur anonyme

26 juil. 2012

A recursive approach if anyone is interested. Only works for singly linked/non circular atm. called like: reverse(head, null); public static ListNode reverse(ListNode curr, ListNode prev) { if (curr == null) { return prev; } else { ListNode temp = curr.next; curr.next = prev; prev = curr; return reverse(temp, prev); } }

1

Utilisateur anonyme

23 juin 2012

public static Node reverse(Node n) { if(n != null) { Node reversed.data = n.data; while(n.next != null) { Node insert; insert.data = n.next; insert.next = reversed; reversed = insert; n = n.next; } return reversed; } return null; }