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

No comments: