Pregunta de entrevista de LinkedIn

Reverse a single linked list.

Respuestas de entrevistas

Anónimo

28 may 2011

public Node reverse(Node head) { Node prev = null; while (head != null) { Node next = head.next; head.next = prev; prev = head; head = next; } return head; }

1

Anónimo

12 sep 2011

Candidate: Using a stack would make it O(n) space. The optimal solution uses O(1) space. Anonymous: Your answer will always return NULL because your exit condition is for head == null and then you return head. I don't think the below is optimal - feels like I should be able to eliminate at least one variable: void reverseList(Node **ppHead) { ASSERT(ppHead != NULL); if(!ppHead) { return; } Node *pPrev = NULL; Node *pCur = *ppHead; while(pCur) { Node *pNext = pCur->pNext; pCur->pNext = pPrev; pPrev = pCur; pCur = pNext; } *ppHead = pCur; }

Anónimo

2 nov 2009

There are multiple ways. You can use a stack or do pointer arithmetic. The interviewer came with a cheat sheet and would insist on pointer arithmetic only.