C++算法与设计,包过!!
/*-----------6.(1)交换二叉树中所有结点的左右子树-------------
#include <iostream>
// 二叉树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 交换左右子树的函数
void swapSubtrees(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
swapSubtrees(root->left);
swapSubtrees(root->right);
}
// 前序遍历函数用于打印二叉树
void preOrderTraversal(TreeNode* root) {
if (root!= NULL) {
std::cout << root->val << " ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
}
int main() {
// 构建一个简单的二叉树示例
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
std::cout << "原始二叉树前序遍历: ";
preOrderTraversal(root);
swapSubtrees(root);
std::cout << "\n 交换后二叉树前序遍历: ";
preOrderTraversal(root);
return 0;
}
*/
/*----------6.(2)以孩子兄弟表示法做存储结构,求树中结点x的第i个孩子-----------
#include <iostream>
// 孩子兄弟表示法的节点结构
struct CSNode {
int val;
CSNode* firstChild;
CSNode* nextSibling;
CSNode(int x) : val(x), firstChild(NULL), nextSibling(NULL) {}
};
// 查找第 i 个孩子的函数
CSNode* findIthChild(CSNode* x, int i) {
CSNode* child = x->firstChild;
while (child && i > 1) {
child = child->nextSibling;
i--;
}
return child;
}
int main() {
// 构建示例树
CSNode* root = new CSNode(1);
CSNode* node2 = new CSNode(2);
CSNode* node3 = new CSNode(3);
CSNode* node4 = new CSNode(4);
CSNode* node5 = new CSNode(5);
root->firstChild = node2;
node2->nextSibling = node3;
node2->firstChild = node4;
node3->firstChild = node5;
CSNode* target = root;
int i = 2; // 要找的第 i 个孩子
CSNode* ithChild = findIthChild(target, i);
if (ithChild) {
std::cout << "节点 " << target->val << " 的第 " << i << " 个孩子是: " << ithChild->val << std::endl;
} else {
std::cout << "节点 " << target->val << " 没有第 " << i << " 个孩子" << std::endl;
}
return 0;
}
*/
/*--------6.(3)二叉树采用二叉链表作为存储结构,输出根结点到每个叶子结点的路径---------
#include <iostream>
#include <queue>
#include <vector>
// 二叉树节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 深度优先搜索函数
void dfs(TreeNode* root, std::vector<int>& path) {
if (root == NULL) {
return;
}
path.push_back(root->val);
// 如果是叶子节点,输出路径
if (root->left == NULL && root->right == NULL) {
for (int i = 0; i < path.size(); i++) {
std::cout << path[i] << " ";
}
std::cout << std::endl;
}
dfs(root->left, path);
dfs(root->right, path);
path.pop_back();
}
// 广度优先搜索函数
void bfs(TreeNode* root) {
if (root == NULL) {
return;
}
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
std::vector<int> path;
while (node!= NULL) {
path.push_back(node->val);
if (node->left == NULL && node->right == NULL) {
for (int i = 0; i < path.size(); i++) {
std::cout << path[i] << " ";
}
std::cout << std::endl;
}
if (node->left!= NULL) {
q.push(node->left);
}
if (node->right!= NULL) {
q.push(node->right);
}
node = q.front();
q.pop();
}
}
}
int main() {
// 构建二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
std::cout << "深度优先搜索结果:" << std::endl;
std::vector<int> path;
dfs(root, path);
std::cout << "广度优先搜索结果:" << std::endl;
bfs(root);
return 0;
}
*/
/*-----------5.(1)将一维数组A[n]中所有奇数移到偶数之前------------
#include <iostream>
// 交换两个元素的函数
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 移动奇数到偶数之前的算法
void moveOddBeforeEven(int A[], int n) {
int left = 0;
int right = n - 1;
while (left < right) {
while (A[left] % 2!= 0 && left < right) {
left++;
}
while (A[right] % 2 == 0 && left < right) {
right--;
}
if (left < right) {
swap(&A[left], &A[right]);
left++;
right--;
}
}
}
int main() {
int A[] = {12, 7, 18, 3, 11, 6};
int n = sizeof(A) / sizeof(A[0]);
std::cout << "原始数组: ";
for (int i = 0; i < n; i++) {
std::cout << A[i] << " ";
}
std::cout << std::endl;
moveOddBeforeEven(A, n);
std::cout << "移动后数组: ";
for (int i = 0; i < n; i++) {
std::cout << A[i] << " ";
}
std::cout << std::endl;
return 0;
}
*/
/*-----5.(2)设计一个C++算法,将一维数组A[n]中所有元素以A[n-1]为参考量分为左右两部分,
其中左半部分的元素值均小于或等于A[n-1],右半部分的元素值均大于A[n-1],
要求结果仍存放在数组A中
#include <iostream>
// 划分函数
int partition(int A[], int low, int high) {
int pivot = A[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (A[j] <= pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i + 1], A[high]);
return (i + 1);
}
// 主要算法函数
void divideArray(int A[], int n) {
int pivotIndex = n - 1;
int partitionIndex = partition(A, 0, n - 1);
}
int main() {
int A[] = {12, 8, 15, 6, 10, 9};
int n = sizeof(A) / sizeof(A[0]);
std::cout << "原始数组: ";
for (int i = 0; i < n; i++) {
std::cout << A[i] << " ";
}
std::cout << std::endl;
divideArray(A, n);
std::cout << "划分后数组: ";
for (int i = 0; i < n; i++) {
std::cout << A[i] << " ";
}
std::cout << std::endl;
return 0;
}
*/
/*---------5.(4)用三元组表表示,计算转置矩阵
#include <iostream>
#include <vector>
using namespace std;
// 三元组结构体
struct Triple {
int row;
int col;
int value;
};
// 计算转置矩阵的函数
vector<Triple> transposeMatrix(vector<Triple> A) {
vector<Triple> B;
for (const Triple &t : A) {
Triple newTriple = {t.col, t.row, t.value};
B.push_back(newTriple);
}
return B;
}
int main() {
// 示例三元组表表示的矩阵 A
vector<Triple> A = {
{1, 2, 3},
{2, 3, 4},
{3, 4, 5}
};
vector<Triple> B = transposeMatrix(A);
// 输出转置后的三元组表 B
for (const Triple &t : B) {
cout << "(" << t.row << ", " << t.col << ", " << t.value << ")" << endl;
}
return 0;
}
*/
//---------------4.String----------------------
/*------4.(1)统计一个字符串中各个不同字符出现的频度
#include <iostream>
#include <string>
#include <unordered_map>
void countCharacterFrequency(const std::string& str) {
std::unordered_map<char, int> frequencyMap;
for (const char& c : str) {
if (frequencyMap.find(c)!= frequencyMap.end()) {
frequencyMap[c]++;
} else {
frequencyMap[c] = 1;
}
}
for (const auto& pair : frequencyMap) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
}
int main() {
std::string str = "hello world";
countCharacterFrequency(str);
return 0;
}
*/
/*---------4.(3)编写算法,实现字符串的逆转----------
#include <iostream>
#include <string>
template<typename T>
class StringReverser {
public:
T reverseString(T str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
std::swap(str[i], str[len - i - 1]);
}
return str;
}
};
int main() {
StringReverser<std::string> reverser;
std::string str = "hello";
std::string reversedStr = reverser.reverseString(str);
std::cout << "Reversed string: " << reversedStr << std::endl;
return 0;
}
*/
/*----------4.(2)统计字串t在主串s中出现的次数
#include <iostream>
#include <string>
template<typename T>
class OccurrenceCounter {
public:
int countOccurrences(T s, T t) {
int count = 0;
int sLen = s.length();
int tLen = t.length();
for (int i = 0; i <= sLen - tLen; i++) {
if (s.substr(i, tLen) == t) {
count++;
}
}
return count;
}
};
int main() {
OccurrenceCounter<std::string> counter;
std::string s = "hellohellohello";
std::string t = "hello";
int occurrences = counter.countOccurrences(s, t);
std::cout << "字符串 '" << t << "' 在字符串 '" << s << "' 中出现的次数为: " << occurrences << std::endl;
return 0;
}
*/
/*----------3.(1)把一个十进制正整数转换为十六进制数输出--------
#include <iostream>
void decimalToHexadecimal(int decimalNumber) {
std::string hexadecimal;
while (decimalNumber > 0) {
int remainder = decimalNumber % 16;
if (remainder < 10) {
hexadecimal = char('0' + remainder) + hexadecimal;
} else {
hexadecimal = char('A' + remainder - 10) + hexadecimal;
}
decimalNumber /= 16;
}
std::cout << "十进制数 " << decimalNumber << " 转换为十六进制为: " << hexadecimal << std::endl;
}
int main() {
int num = 255;
decimalToHexadecimal(num);
return 0;
}
*/
/*---------3.(2)输入一个字符串,判断其是否为回文-----------
#include <iostream>
#include <string>
bool isPalindrome(const std::string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left]!= str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
std::string str = "racecar";
if (isPalindrome(str)) {
std::cout << str << " 是回文。" << std::endl;
} else {
std::cout << str << " 不是回文。" << std::endl;
}
return 0;
}
*/
/*-----3.(4)利用栈与队列成员函数,将一个队列中的元素倒置------
#include <iostream>
#include <queue>
#include <stack>
void reverseQueue(std::queue<int>& queue) {
std::stack<int> stack;
while (!queue.empty()) {
stack.push(queue.front());
queue.pop();
}
while (!stack.empty()) {
queue.push(stack.top());
stack.pop();
}
}
int main() {
std::queue<int> queue;
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
std::cout << "原始队列: ";
while (!queue.empty()) {
std::cout << queue.front() << " ";
queue.pop();
}
std::cout << std::endl;
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
reverseQueue(queue);
std::cout << "倒置后的队列: ";
while (!queue.empty()) {
std::cout << queue.front() << " ";
queue.pop();
}
std::cout << std::endl;
return 0;
}
*/
/*-----------括号匹配的检测---------
#include <iostream>
#include <stack>
#include <string>
bool isBracketMatching(const std::string& str) {
std::stack<char> s;
for (char c : str) {
if (c == '(' || c == '[' || c == '{') {
s.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (s.empty()) {
return false;
}
char top = s.top();
s.pop();
if ((c == ')' && top!= '(') || (c == ']' && top!= '[') || (c == '}' && top!= '{')) {
return false;
}
}
}
return s.empty();
}
int main() {
std::string str;
std::cout << "请输入括号字符串: ";
std::cin >> str;
if (isBracketMatching(str)) {
std::cout << "括号匹配" << std::endl;
} else {
std::cout << "括号不匹配" << std::endl;
}
return 0;
}
*/