Microsoft interview question

Reverse a linked list

Interview Answers

Anonymous

20 Jan 2010

Base1 is the original linked list Initialize Temp and Base2 pointers. Base2 points to Null. While Base1-> Next is not Null Set Temp = New Link Set Temp.Data = Base1.Data Set Temp->Next = Base2. Set Base2 = Temp Set Base1 = Base1->Next End While As it moves through Base1, it adds a copy of the link to the beginning of Base2.

Anonymous

13 Nov 2010

To reverse "in place" a double-linked list, just re-point each element's links (previous becomes next, next becomes previous) - also don't forget to re-point list's head and tail pointers. //get current head P1 = list->head //swap head and tail Head = list->head //pointer to current head element Tail = list->tail //pointer to current tail element list->head = Tail; //set the new head to point at current tail list->tail = Head; //set the new tail to point at old head //Swap each element's links to point in reverse direction while (P1) { P2 = P1->next P1->next = P1->prev P1->prev = P2 ? P2->prev : NULL P1 = P2 } ---------------------------------------------------------- To reverse "in place" a single-linked list, just re-point each element's next pointer to its previous element - also don't forget to re-point list's head pointers to its old tail. //get current head P1 = list->head Head = list->head //pointer to current head element //Swap each element's links to point in reverse direction previous = NULL while (P1) { P2 = P1->next P1->next = previous previous = P1 P1 = P2 } list->head = previous //last non-NULL element

Anonymous

31 Oct 2015

Use 3 pointers