Question
|
Difficulty Level:
1
|
Solution
|
Explanation Quality:1
|
Simple question with simple answer often asked on interviews.
Important point is to do the reversal in place i.e. with the given array and not
by declaring another array.
We declare two pointers, each pointing to the start and the end of array. Next we
swap the values pointed to by the two pointers. We next decrement the end pointer
and increment the start pointer.
We keep on swapping values until the two pointers meet up, which will happen if
there are an odd number of elements in the array. In case there are an even number
of elements like in our example then the stop condition will be signalled when the
pointers cross eachother i.e. the end pointer becomes less than the start pointer
or said another way the start pointer becomes greater than the end pointer. Here's
the code:
int i = 0;
int j = length_of_string - 1; //array index starts from 0
while(i<=j){
temp = string[i];
string[i] = string[j];
string[j] = string[i];
}
Note that another variation of this question asks to reverse the words in a sentence,
that is a bit harder to do since the simple reversal of the string also reverses
the word that is "cat" becomes "tac".
|