Apple interview question

How would you reverse a singly-linked list?

Interview Answers

Anonymous

20 Oct 2015

public void reverse() { Node temp1 = head.next; Node temp2 = temp1.next; head.next = null; temp1.next = head; // Make head the last node while(temp2.next != null){ Node link = temp2.next; temp2.next = temp1; //Increment the positions temp1 = temp2; temp2 = link; } // Reassign the head if(temp2.next == null){ temp2.next = temp1; head = temp2; } }

4

Anonymous

23 Jan 2016

Recursive anser: var root:Node //Assuming there is a variable called root. func reverse(first:Node) { if first.next == nil { return } let oldRoot = root root = first.next! first.next = first.next!.next root.next = oldRoot reverse(first) }

Anonymous

29 June 2016

+ (Node *)reverse:(Node *)root { if (!root) { return nil; } if (!root.nextl) { return root; } Node *newRoot = [Node reverse:root.next]; root.next.next = root; root.next = nil; return newRoot; }