VMWare Inc Interview Question
Software Engineer / DevelopersI finaly figured out three solutions to this:
1. if you are allowed to use only one temp pointer
keep swaping elements i.e. 1 and 2 , then 2 and 3 , then 3 and 4...sna so on...till 1st elemet reaches nth position.
againuse the same funda for swap but this time swap only n-1 times.
This method is little slower.
2. Conventional way.
static void Reverse(struct node** headRef) {
struct node* result = NULL;
struct node* current = *headRef;
struct node* next;
while (current != NULL) {
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
}
*headRef = result;
}
3. Use Stacks or recursive functions.
you can use recursive rutines here..same as stack as recursive functions internally uses stacks
void RecursiveReverse(struct node** headRef) {
struct node* first;
struct node* rest;
if (*headRef == NULL) return; // empty list base case
first = *headRef; // suppose first = {1, 2, 3}
rest = first->next; // rest = {2, 3}
if (rest == NULL) return; // empty rest base case
RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3} case
// after: rest = {3, 2}
first->next->next = first; // put the first elem on the end of the list
first->next = NULL; // (tricky step -- make a drawing)
*headRef = rest; // fix the head pointer
}
Hi can u plz send that code
- Amit February 28, 2007