您的位置:首页 > 编程语言 > C语言/C++

Cracking The Coding Interview 3rd -- 1.2

2014-01-13 10:33 453 查看
Implement a function void resverse(char* str) in C or C++ which reverse a null-terminated string.

Solution 1:

We could implement the function in place with only one iteration by swapping
First
and Last elements in string every time. 

Header file

#ifndef __QUESTION_1_2_H_CHONG__
#define __QUESTION_1_2_H_CHONG__

class Question1_2 {
public:
void reverse(char* str, int size);
int run();
private:
void swap(char* c1, char* c2);
void swap2(char* c1, char* c2);
};

#endif // __QUESTION_1_2_H_CHONG__


Source file
#include "stdafx.h"
#include <iostream>
#include "Question1_2.h"

using namespace std;

void Question1_2::reverse(char* str, int size)
{
// As null-terminated, we do reverse only if size >= 3
if (size<3) {
return;
}

int front = 0;
int end = size-2;
while(front<end) {
swap(str+front, str+end);
swap2(str+front, str+end);
front++;
end--;
}
}

int Question1_2::run()
{
char str[] = "Hello, Chong!";
reverse(str, sizeof(str)/sizeof(*str));
cout << str << endl;

return 0;
}

void Question1_2::swap(char* c1, char* c2)
{
char c = *c1;
*c1 = *c2;
*c2 = c;
}

// swap two addresses with 0 addtional space
void Question1_2::swap2(char* c1, char*c2)
{
if(c1!=c2) {
*c1 = *c1 ^ *c2;
*c2 = *c2 ^ *c1;
*c1 = *c1 ^ *c2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息