Question 1. Implement a linked list reverse function [6]
Suppose we have the following definition for a list node and prototype for a function:
struct Node { int data; Node *next, *prev; }; | bool Reverse(Node* &front, Node* &back); |
Provide an appropriate implementation of the function. (You can choose between reorganizing the nodes themselves or simply moving the data values within the nodes.)
SAMPLE SOLUTION 1 walk towards middle from ends bool Reverse(Node* &front, Node* &back) { // use two nodes to walk from the ends towards // the middle, swapping values as they go // stop and return true if they meet, // return false otherwise // start at the ends of the list Node *forward = front; Node *backward = back; while ((forward != NULL) && (backward != NULL)) { // if the two pointers are the same then they have met // in the middle of an odd length list, so return true if (forward == backward) return true; // check for a broken list: front != back // but one of the pointers is null if ((front == NULL) || (back == NULL)) return false; // otherwise swap their values int temp = forward->data; forward->data = backward->data; backward->data = temp; // if forward and backward are adjacent then they have met // in the middle of an even length list, so return true if (forward->next == backward) return true; // otherwise move both of them one spot closer to the middle forward = forward->next; backward = backward->prev; } // if we get out of the loop then one or both pointers // reached an endpoint without ever meeting each other return false; } | SAMPLE SOLUTION 3: recursive bool Reverse(Node* &front, Node* &back) { // base case if (front == back) return true; // check for a broken list: front != back // but one of the pointers is null if ((front == NULL) || (back == NULL)) return false; // pull off front item Node *oldfront = front; front = front->next; front->prev = NULL; // call recursively if (!Reverse(front, back)) return false; // put old front item on the back back->next = oldfront; oldfront->prev = back; oldfront->next = NULL; back = oldfront; return true; } |