Morgan Stanley Interview Question
Country: India
You can have custom linked list with each element of the link list would be array of specific size . Once the number of elements reached to the size of array, it would add another link list element containing another array.
It will require little complex algorithm to locate the linked list element based on [array_size]%index = linked list element
remainder of above would then be the indexed element inside the array of the linked list element.
It is somewhat similar to tiling in parallel programming.
Write code to overload the [] operator and you can literally rewrite the non-older-deletion version of vector in C++.
#define SIZE 10
struct node
{
int a[SIZE];
struct node * next;
};
typedef struct node Node;
class safearay
{
private:
Node *list;
public:
safearay()
{
list = new Node;
list->next = NULL;
}
int &operator[](int i)
{
if(i == 0)
return start->a[0];
int temp = i / Size;
Node* start = list;
while(temp && start != NULL)
{
start = start->next;
temp--;
}
if(temp == 0)
return start->a[i%SIZE];
else
{
while(temp)
{
Node *tempNode = new Node;
tempNode->next = NULL;
start->next = tempNode;
start = tempNode;
temp--;
}
return start->a[i%SIZE];
}
}
};
public class ArrayResize {
public static void main(String []args) {
Object[] originalArray = new Object[5];
originalArray[0] = 10;
originalArray[1] = 20;
originalArray[2] = 30;
Object[] largerArray = Arrays.copyOf(originalArray, 10);
largerArray[3] = 10;
for (int i = 0; i < largerArray.length; i++) {
System.out.println(largerArray[i]);
}
}
}
You just can't.
- Felipe December 08, 2013An array is a contiguous memory segment. So you can't guarantee that a new allocation will return a subsequent memory address.