Showing posts with label data stuctures. Show all posts
Showing posts with label data stuctures. Show all posts

Wednesday, April 25, 2007

#31

How can you reverse a linked list without using any more memory?

Answer:

    iterative
    loop curr->next = prev;
    prev = curr;
    curr = next;
    next = curr->next
    endloop

    recursive
    reverse(ptr)
    if (ptr->next == NULL) return ptr;
    temp = reverse(ptr->next);
    temp->next = ptr;
    return ptr;
    end

Tuesday, April 24, 2007

#2

I am yet to solve this:

An array of size N has distinct values 1…N in random order. You have only operator called rev(X) (where X is any value from 0 to N-1) which reverses all values from 0 to X (example values 2,3,1,4 and rev(2) gets you 1,3,2,4). Our objective is to sort the array using minimum number of Rev(X) functions. How many permutations of N size array require exactly N number of rev(X) operators to get sorted?