forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-2-edi5-reverseString.cpp
39 lines (34 loc) · 837 Bytes
/
1-2-edi5-reverseString.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* Cracking the coding interview edition *5* old one
* 1.2 Reverse a string when you are a pass a null terminated C string.
*/
#include<iostream>
#include<cstring>
#include<generic.h>
void reverse1( char * str)
{
int len = std::strlen(str);
for ( int i = 0; i < len/2; ++i ) {
algo::swap( str[i], str[len - i - 1] );
}
}
void reverse2( char *str ) {
if ( !str )
return;
char *p = str;
char *q = str;
while (*q) ++q;
--q;
//q now points to last char and p points to first char
while ( p < q )
std::swap( *p++, *q-- );
}
int main()
{
char str[] = "abcdefghijklmnopqrstuvwxyz";
reverse1(str);
std::cout << "On reversing it once: " << str << std::endl;
reverse2(str);
std::cout << "On reversing it again: " << str << std::endl;
return 0;
}