InterviewSolution
Saved Bookmarks
| 1. |
Reverse the Linked List. Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL |
|
Answer» Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3. While you travel the linked list, change the current node's next pointer to point to its previous element. reference to the previous nodes should be stored into a temp variable as shown so that we don’t lose track of the swapped node. You also need another pointer to STORE the next node before changing the reference. Also when we are done return the new head of the REVERSED list. /* Function to reverse the linked list */static VOID reverse(struct Node** head_ref) { struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { // store next next = current->next; // reverse curr node pointer current->next = prev; // move pointer one position ahead prev = current; current = next; } *head_ref = prev; } |
|