Friday, August 08, 2014

Interviews -- Reverse Singly Linked List, C++

Just seriously struggled through an interview on the phone. It's always the simple programming problems that seem the hardest when someone is watching you do it.

The question was "Write a simple function to reverse a linked list" and I couldn't get it right until 3 minutes after the interview was over. Every. Single. Time.

So here is the code I ended up with, given this basic Linked list.

struct List {
   int value;
   mySingleLinked* next;
};

Seems simple, right? See the comments ;)

// arg. i'm an idiot
List reverseLinkedList(List* head) {
    List *tempList, *nextList;

tempList = 0;
nextList = 0;

while (head != 0)
{
nextList = head->next;
head->next = tempList;
tempList = head;
head = nextList;
}
return tempList;
}

No comments: